
上QQ阅读APP看本书,新人免费读10天
设备和账号都新为新人
2.5 global对象
ES5的顶层对象本身也是一个问题,因为它在各种实现中是不统一的。
· 在浏览器中,顶层对象是window,但Node和Web Worker没有window。
· 在浏览器和Web Worker中,self也指向顶层对象,但是Node没有self。
· 在Node中,顶层对象是global,但其他环境都不支持。
同一段代码为了能够在各种环境中都取到顶层对象,目前一般是使用 this 变量,但是也有局限性。
· 在全局环境中,this会返回顶层对象。但是,在Node模块和ES6模块中,this返回的是当前模块。
· 对于函数中的this,如果函数不是作为对象的方法运行,而是单纯作为函数运行,this会指向顶层对象。但是,严格模式下,this会返回undefined。
· 不管是严格模式,还是普通模式,new Function(′return this′)()总会返回全局对象。但是,如果浏览器用了CSP(Content Security Policy,内容安全政策),那么eval、new Function这些方法都可能无法使用。
综上所述,很难找到一种方法可以在所有情况下都取到顶层对象。以下是两种勉强可以使用的方法。


现在有一个提案(github.com/tc39/proposal-global),在语言标准的层面引入 global 作为顶层对象。也就是说,在所有环境下,global都是存在的,都可以拿到顶层对象。
垫片库 system.global(github.com/ljharb/System.global)模拟了这个提案,可以在所有环境下拿到global。

上面的代码可以保证,在各种环境中global对象都是存在的。

上面的代码将顶层对象放入变量global中。