Defining an implementation independent version of the global object in JavaScript

前端 未结 3 1018
伪装坚强ぢ
伪装坚强ぢ 2021-01-03 00:14

I\'m trying to define the global object in JavaScript in a single line as follows:

var global = this.global || this;

The above

3条回答
  •  天涯浪人
    2021-01-03 01:06

    After reading Esailija and Raynos' answers I understood that my code this.global || this will not work for all cases in node.js; and that it may even fail in browsers if a variable called global already exists in the global scope.

    Esailija pointed out that this.global is not really the global object, stating instead that this is the global object in RingoJS; and although I understand his arguments, for my purposes I require this.global and not this.

    Raynos suggested that I hard code feature detection for every CommonJS environment. However since I'm currently only supporting RingoJS and node.js, I only need to test for global and window. Hence I decided to stick with this.global || this.

    Nevertheless, as I said before this.global || this doesn't work for all cases in node.js as I understood from benvie's comments. In the node.js REPL I realized that I require this and not this.global. However, this.global || this expresses this.global. In a node.js module I require this.global and not this. However, it expresses this since this.global is undefined. Hence to solve this problem I finally decided to use the following code:

    (function (global) {
        // javascript framework
    })(typeof global !== "undefined" && global || this);
    

    The reason I'm using this code is because in node.js modules this.global is undefined. Hence we must use global directly. Thus we use typeof global !== "undefined" && global to get the global object in both RingoJS and node.js; and we use this as the global object in browsers (window) and as a default fallback.

    Note: I didn't provide any logic for finding the global object in the node.js REPL because I don't believe that my framework will be used directly within the REPL anyway. However, writing the logic to find it should be fairly trivial once one understands the complications of finding the global object in node.js as benvie pointed out. I know that I don't.

提交回复
热议问题