The ECMAScript proposal “ global ” by Jordan Harband is currently at stage 3. It provides a new standard way of accessing the global object.
您需要 登录 才可以下载或查看，没有帐号？立即注册
Referring to the global object
The following are a few popular ways of referring to the global object:
- Global variables:
- Global variable window: is the classic way of referring to the global object. But it doesn’t work in Node.js and in Web Workers.
- Global variable self: is available in Web Workers and browsers in general. But it isn’t supported by Node.js. Some people use selfto mark code that works in both Web Workers and normal browser contexts.
- Global variable global: is only available in Node.js. Until now!
- thisin global scope: refers to the global object. The only problem is that Node.js modules and ES6 modules have their own scopes, which means that this approach doesn’t work there.
- thisduring a function call in sloppy mode: If you call a function via a function call (and not a method call), its thisrefers to the global object in non-strict mode. In strict mode, it is undefined.
- new Function('return this')(): works in both strict mode and sloppy mode, because the parameters of new Function()are always evaluated in sloppy mode. There is one important caveat: eval, new Function(), etc. are not available if you use CSP (Content Security Policy). That makes this approach unsuited in many cases.
The ECMAScript proposal standardizes the global variable globalfor accessing the global object. It also standardizes that the global object must have Object.prototypein its prototype chain. The following is already true in web browsers today:
Best practices 复制代码
- > Object.prototype.isPrototypeOf(window)
ECMAScript 6 moves away from the global object by providing three new ways for declaring variables that don’t create global properties in global scope (as vardeclarations and function declarations do):
In other words: all properties of the global object are global variables, but not all global variables are properties of the global object. For example (executed in global scope):
- Class declarations
- > var foo;
- > 'foo' in window
- > let bar;
- > 'bar' in window
Therefore, globalwill mostly be relevant for polyfills.
The proposal’s author, Jordan Harband, has written a polyfillfor it.
Using it with CommonJS syntax:
Using it with ES6 module syntax: 复制代码
- var global = require('system.global')();
The package always uses the “most native” approach available ( globalon Node.js etc., windowin normal browser contexts, etc.). 复制代码
- import getGlobal from 'system.global';
- const global = getGlobal();
More information on the global object
下一篇：Segmentation Protection in Intel Processor