[英]What is globalThis in Javascript? What will be the ideal use case for this?
最近我在 Javascript 中遇到了globalThis
。 如果从函数中调用它,我不确定它会如何表现。 每次它都返回window
对象。 如果是这样,那我们为什么不直接使用window
对象。 使用globalThis
什么必要?
如果我从函数调用 ,则它返回窗口对象示例:
(function test(){
console.log(globalThis); // returns window
})();
var obj = {
key1: function(){
console.log(globalThis)
},
key2: ()=>{
console.log(globalThis)
},
key3: function(){
var arrFn = () => {
console.log(globalThis);
}
arrFn();
}
};
obj.key1(); // returns window object
obj.key2(); // returns window object
obj.key3(); // returns window object
我相信globalThis
的内部实现就像下面的代码:
const getGlobalThis = () => {
if (typeof globalThis !== 'undefined') return globalThis;
if (typeof self !== 'undefined') return self;
if (typeof window !== 'undefined') return window;
if (typeof global !== 'undefined') return global;
// Note: this might still return the wrong result!
if (typeof this !== 'undefined') return this;
throw new Error('Unable to locate global `this`');
};
const theGlobalThis = getGlobalThis();
任何人都可以向我解释globalThis
的确切用例吗? 使用它的理想场景是什么?
正如MDN 所说:
global
globalThis
属性包含全局 this 值,它类似于全局对象。
为什么有用:
从历史上看,在不同的 JavaScript 环境中访问全局对象需要不同的语法。 在 Web 上,您可以使用
window
、self
或frames
- 但在 Web Workers 中只有self
可以工作。 在 Node.js 中,这些都不起作用,您必须改用global
。globalThis 属性提供了一种跨环境访问全局“this”值(以及全局对象本身)的标准方法。 与 window 和 self 等类似属性不同,它保证在窗口和非窗口上下文中工作。 通过这种方式,您可以以一致的方式访问全局对象,而无需知道代码在哪个环境中运行。为了帮助您记住名称,只需记住在全局范围内 this 值为 globalThis。
如果您不确定代码将在什么环境中运行,或者不想跟踪它(毕竟,认知开销少是一件好事!),您可以改用globalThis
。
如果您确定您的代码将在什么环境中运行,并且代码永远不会被移植到不同的环境,请随意继续使用window
(或环境的全局对象的适当其他属性)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.