Home >Web Front-end >Front-end Q&A >What are the ways to obtain top-level objects in es6
es6 How to obtain the top-level object: 1. Use the "typeof window !== 'undefined' ? window : (...) ? global : this" method to obtain; 2. Use "var getGlobal = function ( ) {...throw new Error('unable to locate global object');};" method to obtain.
The operating environment of this tutorial: Windows 10 system, ECMAScript version 6.0, Dell G3 computer.
Before ES6, the properties of the top-level object and global variables were equivalent, but in ES6, the top-level object and the global object began to be separated.
The error of undeclared variables cannot be reported at the compilation stage, only at runtime Just known.
It is easy to create global variables without knowing it
The top-level object can be read and written at will
Limitations
In the global environment, this returns the top-level object; In Node modules and ES6 modules, this returns the this in the current module function(1) When simply run as a function, this returns the top-level (2) In strict mode, return undefinednew Function('return this')(); always returns the global object. But if the browser uses CSP, then the eval and new Function methods may not be usedCSP: Content Security Policy, content security policy. It works on resources loaded or executed by the website through a whitelist mechanism, which is defined in the web page through HTTP header information or meta elements. However, it also caused the following problemseval and related functions are disabled.
- Embedded JavaScript code will not be executed.
- Remote scripts can only be loaded through the whitelist.
// 方法1 // 针对 浏览器中 顶层对象是window,但是Node和Web Worker没有window。 ( typeof window !== 'undefined' ? window : ( typeof process === 'object' && typeof require === 'function' && typeof global === 'object' ) ? global : this ); //方法2 // 针对 浏览器和Web Worker中,self也指向顶层对象,但是Node没有self。 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'); };
javascript video tutorial, web front end】
The above is the detailed content of What are the ways to obtain top-level objects in es6. For more information, please follow other related articles on the PHP Chinese website!