質問

グローバルオブジェクトに推奨される方法は、ES5厳密モード未知のホスト環境で

ECMAScriptは、私が知っているグローバルオブジェクトを参照するための組み込み方法を提供しません。もしそうなら、これは私が探している答えです。

既知の環境では、グローバルオブジェクトは通常自己参照プロパティを持ちます。グローバルオブジェクトは vo グローバルオブジェクトのプロパティはグローバル変数です。だから私たちはそれらを使用することができます。のどこからでもグローバルオブジェクトにハンドルを取得できます。

  • Webブラウザでは、windowまたはselfを使用できます。

  • Node.jsでは、globalを使用できます。

    しかし、これは必ずしもすべてのホスト環境ではそうではありません。私が知っている限り、Windowsスクリプトホストはグローバルオブジェクトにアクセスする方法を提供しません。 WSHでグローバルオブジェクトを取得するための推奨される方法は、オブジェクトに解決されないコンテキストでthisキーワードを使用することです。例えば:

    var GLOBAL = (function(){return this}());
    
    .

    この手法は、未定義のthis厳密にはグローバルオブジェクトを参照しないため、厳密なモードでは機能しません。モード

    これが厳密モードコード内で評価されている場合、この値はオブジェクトに強制されません。 aこのnullまたは未定義の値は、グローバルオブジェクトに変換されず、プリミティブ値はラッパーオブジェクトに変換されません。この値は、関数呼び出し(function.prototype.applyおよびfunction.prototype.callを使用して行われた呼を含む)を介して渡されます。この値がオブジェクトに渡されません(10.4.3,11.1.1,15.3.4.3,15.3。 4.4)

    予想通り、次のコードはundefinedになります。

    (function(){
        "use strict";
        var GLOBAL = (function(){return this}());
        console.log(GLOBAL);
    }());
    
    .


    それで、厳密なモードにかかわらず、環境内のグローバルオブジェクトへのハンドルを取得するのに適した方法は何ですか?

    ところで、マイの現在のアプローチは、このようなグローバルオブジェクトを参照するグローバル変数のためにスニフすることです。

    var self, window, global = global || window || self;
    
    .

    ...そしてそれからglobalを使用してください。私はこれがいくつかの理由で悪い解決策であると思います、そのほとんどはかなり明白であり、そしてそれはWSH問題に対処しません。

役に立ちましたか?

解決

In ES5, you can get a reference to global object from within strict mode via indirect eval call:

"use strict";
var global = (1,eval)('this');

Take a look at my article; particularly at this section on strict mode.

他のヒント

In global code, the thisBinding is set to the global object regardless of strict mode. That means you can pass it from there into your module IEFE:

// "use strict"; or not
(function(global) {
    "use strict";
    …
    console.log(global);
    …
}(this));

In strict mode, the way to get a reference to the global object is to assign a variable in the global object referencing itself.

That is this means the global object when in the global context, so the solution is simply:

"use strict";
var global = global || this;
(function() { global.hello = "world"; })();
console.log(hello); // Outputs 'world' as expected

This does mean that you have to pollute the global namespace with a reference to itself, but like you say, it should already have been there.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top