【英】globalThis: 统一的机制来访问JavaScript全局对象

87 阅读1分钟

JavaScript is increasingly used in a wide variety of environments, like web browser and servers.

Each environment has its own object model and provides a different syntax to access the global object. In the web browser, for example, the global object is accessible via windowself, or frames. In Node.js, however, these properties don’t exist, and you must use global instead. In Web Workers, only self is available. See below.

window

The window property is used to refer to the global object of the current document in the browser environment.

var a = 1;
console.log(window.a) // output: 1

self

The Web Workers API doesn’t have a Window object because it has no browsing context. Instead, it provides the WorkerGlobalScope interface containing the data that’s normally carried by window.

var a = 1;
console.log(self.a) // output: 1

frames

Another way to access the global object in the browser environment is to use the frames property, which works similar to self and window.

console.log(frames);    // output: Window {...}

global

In Node.js, you can access the global object using the global keyword.

console.log(global);    // output: Object [global] {...}

this

In browsers, you can use the this keyword at the top level of your program to reference the global object.

this.foo = 123;
console.log(this.foo === window.foo);    // => true

globalThis

These different methods to access the global object can be annoying. Instead, we can use globalThis, which defines a standard global property. By using globalThis, your code will work in window and non-window contexts. Generally, when you’re not sure in what environment your code will be used, or when you want to make your code executable in different environments, the globalThis property comes in very handy.

var a = 1;
console.log(globalThis.a) // output: 1