The top-level object

The top-level object refers to the Window object in the browser and the Global object in Node. Prior to ES5, attributes of top-level objects were equivalent to global variables.

window.a = 1;
a // 1

a= 2;
window.a //2
Copy the code

Above, the assignment of attributes to top-level objects is consistent with the assignment of global variables. In order to change this, ES6 stipulates that global variables declared by var and function commands are still attributes of top-level objects in order to maintain compatibility. On the other hand, it also states that global variables declared by let, const, and class are not attributes of the top-level object.

GlobalThis object

The Javascript language has a top-level object that provides a global scope in which all code is run, but top-level objects are not uniform across implementations.

  • The top layer object of the browser is window, Node and Web worker have no window
  • In browsers and Web workers, self also points to the top-level object, but Node has no self
  • In Node, the top-level object is global, but there is no global in any other environment

In order for the same code to be able to fetch the top-level object in all circumstances, it is now common to use this object, but there are limitations.

  • In the global context, this returns the top-level object. However, in Node and ES6 modules, the current module is returned.
  • This in a function, if the function is not run as a method on an object, but simply as a function, this points to the global object. But in strict mode, it’s going to return this it’s going to return undefined.

The solution

// Ensure that this returns all top-level objects // method one (typeof window! = ='undefined'
   ? window
   : (typeof process === 'object' &&
      typeof require === 'function' &&
      typeof global === 'object')? global : this); Var getGlobal = //function () {
  if(typeof self ! = ='undefined') { return self; }
  if(typeof window ! = ='undefined') { return window; }
  if(typeof global ! = ='undefined') { return global; }
  throw new Error('unable to locate global object');
};
Copy the code

Refer to the link

ECMAScript introduction to 6