ES5 's top-level object itself is also a problem, because it is not unified in various implementations.
- Inside the browser, the top-level object is
window
, but Node and Web Worker do not window
.
- Inside the browser and Web Worker,
self
It also points to the top-level object, but Node does not self
.
- Node, the top-level object is
global
, but no other environment is supported.
The same piece of code in order to be able to take the top-level objects in various environments, now generally use this
variables, but there are limitations.
- In the global environment, the
this
top-level object is returned. However, in the Node module and in the ES6 module, this
the current module is returned.
- function,
this
if the function is not run as a method of an object, but simply runs as a function, this
it points to the top-level object. However, in strict mode, this this
is returned undefined
.
- Whether it is strict mode or normal mode,
new Function(‘return this‘)()
the global object is always returned. However, eval
new Function
These methods may not be available if the browser uses a CSP (content security Policy).
In summary, it is difficult to find a way to take the top-level object in all cases. Here are two methods that are barely available.
//Method One(typeofWindow!== ' undefined '?window: (typeofProcess = = = ' object ' &&typeofrequire = = = ' function ' &&typeofGlobal = = = ' object ') ?Global: This);//Method TwovarGetglobal =function () { if(typeofSelf!== ' undefined ') {returnSelf ;} if(typeofWindow!== ' undefined ') {returnwindow;} if(typeofGlobal!== ' undefined ') {returnGlobal;} Throw NewError (' Unable to locate global object ');};
Now there is a proposal, at the level of the language standard, to introduce global
as the top-level object. In other words, in all environments, global
there is the existence of a top-level object from which it can be obtained.
The Shim Library system.global
simulates this proposal and can be obtained in all environments global
.
// CommonJS require (' System.global/shim ') (); // ES6 Module import shim from ' System.global/shim '; Shim ();
The above code ensures that global
objects are present in various environments.
// the writing of CommonJS var global = require (' System.global ') (); // ES6 Module import getglobal from ' System.global '= Getglobal ();
The above code puts the top-level object into a variable global
.
(Above is ECMAScript 6 introductory text)
Two--global objects of ES6 Records