globalThis

發布於 · 標籤為 ECMAScript ES2020

如果您之前曾撰寫 JavaScript 供網路瀏覽器使用,您可能曾使用 window 來存取全域 this。在 Node.js 中,您可能曾使用 global。如果您曾撰寫必須在任一環境中運作的程式碼,您可能已偵測到哪些可用,然後使用它 — 但要檢查的識別碼清單會隨著您想要支援的環境和使用案例數量而增加。它會很快失控

// A naive attempt at getting the global `this`. Don’t use this!
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();

有關上述方法為何不足的更多詳細資訊(以及更複雜的技術),請閱讀 通用 JavaScript 中令人驚恐的 globalThis polyfill

globalThis 提案 引進了一種統一的機制,用於在任何 JavaScript 環境(瀏覽器、Node.js 或其他環境?)中存取全域 this,不論腳本目標(傳統腳本或模組?)為何。

const theGlobalThis = globalThis;

請注意,現代程式碼可能根本不需要存取全域 this。使用 JavaScript 模組,您可以宣告式地 importexport 功能,而不是處理全域狀態。globalThis 仍然適用於需要全域存取的 polyfill 和其他函式庫。

globalThis 支援 #