globalThis 对象
在JavaScript
运行环境中,存在一个顶层对象,即是全局运行环境(全局作用域),在browser
环境下,顶层对象指向window
,在node
环境下,顶层对象指向global
,在Web Worker
中,顶层对象又指向self
。而这个顶层对象我们常常又使其与this
挂钩,一般默认使用this
变量即可获得该顶层变量。但由于this
在JavaScript
中又是一个很复杂的变量。因为this
在不同的执行上下文中指向不一,使其在获取顶层对象具有局限性。如在模块中,this
指向该模块;严格模式运行的函数this
是undefined
。因此,出现很多垫片函数获取全局的对象,我们最熟悉的是如下获取顶层对象的方法。
function getGloablThis() {
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');
}
在ES2020
中,提供了globalThis