globalThis
試一試
function canMakeHTTPRequest() {
return typeof globalThis.XMLHttpRequest === "function";
}
console.log(canMakeHTTPRequest());
// Expected output (in a browser): true
值
全域性 this 物件。
globalThis 的屬性特性 | |
|---|---|
| 可寫 | 是 |
| 可列舉 | 否 |
| 可配置 | 是 |
注意: globalThis 屬性是可配置和可寫的,這樣程式碼作者可以在執行不受信任的程式碼時隱藏它,並防止暴露全域性物件。
描述
歷史上,在不同的 JavaScript 環境中訪問全域性物件需要不同的語法。在 Web 上,你可以使用 window、self 或 frames——但在 Web Workers 中,只有 self 會起作用。在 Node.js 中,這些都不起作用,你必須改用 global。this 關鍵字可以在非嚴格模式下執行的函式內部使用,但在模組和嚴格模式下執行的函式內部,this 將是 undefined。你也可以使用 Function('return this')(),但停用 eval() 的環境(如瀏覽器中的 CSP)會阻止以這種方式使用 Function。
globalThis 屬性提供了一種跨環境訪問全域性 this 值(從而訪問全域性物件本身)的標準方式。與 window 和 self 等類似屬性不同,它保證在視窗和非視窗上下文中都能工作。透過這種方式,你可以以一致的方式訪問全域性物件,而無需知道程式碼正在哪個環境中執行。為了幫助你記住這個名字,只需記住在全域性作用域中,this 值就是 globalThis。
注意: globalThis 通常與全域性物件是相同的概念(即,向 globalThis 新增屬性會使它們成為全域性變數)——瀏覽器和 Node 都是如此——但宿主可以為 globalThis 提供一個與全域性物件無關的不同值。
HTML 和 WindowProxy
在許多引擎中,globalThis 將是實際全域性物件的引用,但在 Web 瀏覽器中,由於 iframe 和跨視窗安全考慮,它引用的是實際全域性物件(你無法直接訪問)的 Proxy。這種區別在常見用法中很少相關,但瞭解這一點很重要。
命名
其他幾個流行的命名選擇,如 self 和 global,由於它們可能與現有程式碼產生相容性問題而被排除。有關更多詳細資訊,請參閱語言提案的“命名”文件。
globalThis 字面上就是全域性 this 值。它與非嚴格模式下未透過物件呼叫的函式中的 this 值相同。它也是指令碼全域性作用域中的 this 值。
示例
跨環境搜尋全域性物件
通常,全域性物件不需要顯式指定——它的屬性會自動作為全域性變數訪問。
console.log(window.Math === Math); // true
然而,需要顯式訪問全域性物件的一個情況是向其寫入,通常是為了polyfill的目的。
在 globalThis 之前,獲取環境全域性物件的唯一可靠跨平臺方法是 Function('return this')()。然而,這在某些設定中會導致 CSP 違規,因此作者會使用這樣的分段定義(略微改編自原始 core-js 原始碼)
function check(it) {
// Math is known to exist as a global in every environment.
return it && it.Math === Math && it;
}
const globalObject =
check(typeof window === "object" && window) ||
check(typeof self === "object" && self) ||
check(typeof global === "object" && global) ||
// This returns undefined when running in strict mode
(function () {
return this;
})() ||
Function("return this")();
獲取全域性物件後,我們可以在其上定義新的全域性變數。例如,新增 Intl 的實現
if (typeof globalObject.Intl === "undefined") {
// No Intl in this environment; define our own on the global scope
Object.defineProperty(globalObject, "Intl", {
value: {
// Our Intl implementation
},
enumerable: false,
configurable: true,
writable: true,
});
}
有了 globalThis,就不再需要跨環境額外搜尋全域性物件了。
if (typeof globalThis.Intl === "undefined") {
Object.defineProperty(globalThis, "Intl", {
value: {
// Our Intl implementation
},
enumerable: false,
configurable: true,
writable: true,
});
}
規範
| 規範 |
|---|
| ECMAScript® 2026 語言規範 # sec-globalthis |
瀏覽器相容性
載入中…