gpt4 book ai didi

javascript - Javascript 中的 globalThis 是什么?什么是理想的用例?

转载 作者:行者123 更新时间:2023-12-01 09:12:29 28 4
gpt4 key购买 nike

最近我遇到了globalThis在 Javascript 中。我不确定如果从函数调用它会如何表现。每次返回 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 says :

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


为什么有用:

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.


如果您不确定代码将在什么环境中运行,或者不想跟踪它(毕竟认知开销少是件好事!),您可以使用 globalThis反而。
如果您确定您的代码将在什么环境中运行,并且代码永远不会被移植到不同的环境,请继续使用 window。 (或环境的全局对象的适当其他属性)。

关于javascript - Javascript 中的 globalThis 是什么?什么是理想的用例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57157864/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com