What is globalThis in Javascript? What will be the

2019-07-27 09:30发布

问题:

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?

回答1:

As MDN says:

The global globalThis property contains the global this value, which is akin to the global object.

Why it's useful:

Historically, accessing the global object has required different syntax in different JavaScript environments. On the web you can use window, self, or frames - but in Web Workers only self will work. In Node.js none of these work, and you must instead use global.

The globalThis property provides a standard way of accessing the global 'this' value (and hence the global object itself) across environments. Unlike similar properties such as window and self, it's guaranteed to work in window and non-window contexts. In this way, you can access the global object in a consistent manner without having to know which environment the code is being run in. To help you remember the name, just remember that in global scope the this value is globalThis.

If you don't know for certain what environment the code is going to be run in, or don't feel like keeping track of it (less cognitive overhead is a good thing, after all!), you can use globalThis instead. (though, it'll probably be quite a while before it's implemented natively on enough browsers to be used without a polyfill)

If you know for sure what environment your code is going to be running in, and that the code will never be ported to a different environment, feel free to just keep using window (or the appropriate other property for the environment's global object).