liveBook · Manning

globalThis

As explained in Secrets of the JavaScript Ninja, Third Edition

The standardized JavaScript global binding that references the global object across different execution environments.

globalThis is the standardized way to reference JavaScript’s global object across environments. Attach a property to it when a value needs to be available globally; prefer it to environment-specific names such as window or global unless using an environment-specific API. section 7.4

Listing 7.7 Attaching a value to the global object
// In globals.mts
declare global { #A
  var ninjaName: string; #A
} #A
 
globalThis.ninjaName = "Naruto"; #B
 
// In main.mts
import "./globals.mts"; #C
 
console.log(`It's me, ${ninjaName}!`);

This example attaches ninjaName to globalThis in one module so another module can use the name without importing it. section 7.4

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Defines globalThis and works through a cross-module example, without detailing its implementation.
Examples
Demonstrates setting ninjaName on globalThis in one module and reading it from another.
What you can do after
Apply it by attaching a property to globalThis for access across modules.
How it connects
Connects the global object and global scope with modules and strict mode.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Third Edition. The section links point to the parts of the book it draws on.