【JavaScript】標準內建變數 globalThis
阿新 • • 發佈:2020-07-26
以下內容為學習記錄,可以參考 MDN 原文。
環境
- node v12.18.1
- npm 6.14.5
- vscode 1.46
- Microsoft Edge 83
概念
在以前,從不同的 JavaScript 環境中獲取全域性物件需要不同的語句。
在 Web 中,可以通過 window、self 或者 frames 取到全域性物件,但是在 Web Workers 中,只有 self 可以。
在 Node.js 中,它們都無法獲取,必須使用 global。
在鬆散模式下,可以在函式中返回 this 來獲取全域性物件,但是在嚴格模式和模組環境下,this 會返回 undefined。
globalThis 提供了一個標準的方式來獲取不同環境下的全域性 this 物件(也就是全域性物件自身)。不
像 window 或者 self 這些屬性,它確保可以在有無視窗的各種環境下正常工作。
所以,你可以安心的使用 globalThis,不必擔心它的執行環境。
為便於記憶,你只需要記住,全域性作用域中的 this 就是 globalThis。
示例
在 globalThis 之前,獲取某個全域性物件的唯一方式就是 Function('return this')(),
但是這在某些情況下會違反 CSP 規則,所以,es6-shim 使用了類似如下的方式:
var getGlobal = function () { if (typeof self !== 'undefined') { return self; } if (typeof window !== 'undefined') { return window; } if (typeof global !== 'undefined') { return global; } throw new Error('unable to locate global object'); }; var globals = getGlobal(); if (typeof globals.setTimeout !== 'function') { // 此環境中沒有 setTimeout 方法! }
但是有了 globalThis 之後,只需要:
if (typeof globalThis.setTimeout !== 'function') {
// 此環境中沒有 setTimeout 方法!
}
練習
function canMakeHTTPRequest() {
return typeof globalThis.XMLHttpRequest === 'function';
}
console.log(canMakeHTTPRequest());
// expected output (in a browser): true