javascript 属性
A new property called globalThis gives you cross-platform access to the global object in JavaScript.
名为globalThis的新属性使您可以跨平台访问JavaScript中的全局对象。
Accessing the global property in JavaScript has always posed some difficulty. This is because different platforms have different ways to access it.
在JavaScript中访问全局属性总是带来一些困难。 这是因为不同的平台有不同的访问方式。
Client-side JavaScript uses
window
orself
客户端JavaScript使用
window
或self
Node.js uses
global
Node.js使用
global
Web workers use
self
网络工作者使用
self
This isn’t a huge problem if you’re exclusively writing client-side JavaScript. You could simply write window
to interact with the global object.
如果要专门编写客户端JavaScript,这不是一个大问题。 您只需编写window
即可与全局对象进行交互。
However, the problem arises when you need to write portable JavaScript that works on more than a single platform (eg.: a library like lodash which works in both Node.js and client-side).
但是,当您需要编写可在多个平台上运行的可移植JavaScript时,就会出现问题(例如:像lodash这样的库,它可以在Node.js和客户端中运行)。
The popular solution is to use a shim that uses code like this to determine the available global object:
流行的解决方案是使用填充程序,该填充程序使用如下代码来确定可用的全局对象:
var getGlobal = function () {
if (typeof window !== 'undefined') {
return window; // Client-side JavaScript
}
if (typeof self !== 'undefined') {
return self; // Client-side JavaScript / Web workers
}
if (typeof global !== 'undefined') {
return global; // Node.js
}
};
var __global__ = getGlobal();
if (typeof __global__.alert === 'function') {
console.log('Client-side land!');
} else {
console.log('Node.js land!');
};
使用globalThis (Using globalThis)
Since globalThis
is available in Node.js/client-side/Web workers, interacting with the global object becomes much simpler!
由于globalThis
在Node.js /客户端/ Web工作者中可用,因此与全局对象进行交互变得更加简单!
if (typeof globalThis.alert === 'function') {
console.log('Client-side land!');
} else {
console.log('Node.js land!');
}
Say goodbye to inspecting which platform you’re on! ✌️
告别检查您在哪个平台上! ✌️
结论 (Conclusion)
Currently globalThis
is a Stage-3 ECMAScript Proposal. However, many browsers including Chrome, Firefox, and Safari (desktop/mobile) have already made this new API available!
目前是globalThis
是第3阶段ECMAScript提案。 但是,包括Chrome,Firefox和Safari(台式机/移动设备)在内的许多浏览器已使此新API可用!
For in-depth information about globalThis
checkout Axel Rauschmayer’s blog post 📰
有关globalThis
的深入信息,请globalThis
Axel Rauschmayer的博客文章📰
翻译自: https://www.digitalocean.com/community/tutorials/js-globalthis
javascript 属性