Sas*_*nda 2 javascript ecmascript-6
Recently I have come across about globalThis in Javascript. I am not sure how it is going to behave if it is called from a function. Every time it is returning the window object. if that is the case, then why don't we directly use the window object. What is necessary of using globalThis?
If I call the from a function, then it is returning window object Example:
(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
Run Code Online (Sandbox Code Playgroud)
I believe the internal implementation of globalThis is like the below code:
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();
Run Code Online (Sandbox Code Playgroud)
Can anyone please explain to me the exact use case of the globalThis? What will be the ideal scenario to use this?
正如MDN所说:
全局
globalThis属性包含全局this值,类似于全局对象。
为什么有用:
从历史上看,访问全局对象在不同的JavaScript环境中需要使用不同的语法。在网络上,您可以使用
window,self或frames-,但仅在Web Workers中self有效。在Node.js中,这些都不起作用,而必须使用global。globalThis属性提供了一种跨环境访问全局“ this”值(以及全局对象本身)的标准方法。与window和self之类的类似属性不同,它保证可以在window和非window上下文中工作。这样,您可以以一致的方式访问全局对象,而不必知道代码在哪个环境中运行。为了帮助您记住名称,只需记住在全局范围内,此值为globalThis。
如果您不确定要在什么环境中运行代码,或者不想跟踪它(毕竟,减少认知开销是一件好事!),则可以使用globalThis。(尽管如此,在足够多的浏览器上实现本机实现,而无需使用polyfill可能要花相当长的时间)
如果您确定要在什么环境中运行您的代码,并且永远不会将代码移植到其他环境,请随时继续使用window(或该环境的全局对象的其他适当属性)。