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
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();
Can anyone please explain to me the exact use case of the globalThis
? What will be the ideal scenario to use this?
globalThis
is there in every browser. – Popover