| 全局对象 | 浏览器 | Node | Web Worker |
|---|---|---|---|
| window | 有 | ||
| self | 有 | 有 | |
| global | 有 |
Node和浏览器通用的获取方式:
1.自执行函数在非严格模式下,内部this指向顶层对象
缺点:严格模式指向为undefined
;(function(){
console.log(this);
}());
let MyGlobal = (function(){
return this;
})();
2.new Function
缺点: 如果浏览器用了 CSP(Content Security Policy,内容安全策略), 那么eval、new Function这些方法都可能无法使用
console.log(new Function('return this')());
3.利用typeof检测不存在的值不会报错的机制(注意: typeof在暂时性死区[temporal dead zone]内会报错)
let MyGlobal = 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');
}();
4.globalThis
缺点: ES2020中发布,老版本浏览器不兼容
console.log(globalThis);