globalThis

公開 · タグ付け: ECMAScript ES2020

以前に Web ブラウザで使用するため JavaScript を記述したことがある場合は、グローバル this にアクセスするために window を使用したことがあるでしょう。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 ポリフィル をお読みください。

globalThis の提案は、スクリプトの目標(従来のスクリプトかモジュールか)に関係なく、すべての JavaScript 環境(ブラウザ、Node.js、またはその他)でグローバル this にアクセスするための統一されたメカニズムを導入いたします。

const theGlobalThis = globalThis;

最新のコードでは、グローバル this にアクセスする必要がない場合があることに注意してください。JavaScript モジュールを使用すると、グローバルステートを操作する代わりに機能を宣言的に import および export できます。globalThis は、グローバルアクセスを必要とするポリフィルやその他のライブラリに役立ちます。

globalThis サポート #