Defining an implementation independent version of the global object in JavaScript

前端 未结 3 1052
伪装坚强ぢ
伪装坚强ぢ 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条回答
  •  萌比男神i
    2021-01-03 01:06

    Implementation independant version is not trivial

    (function (global) {
        // javascript framework
    })(
       this && this.global || // ringoJS
       typeof root !== "undefined" && root || // node.js
       typeof global !== "undefined" && global || // more node.js
       typeof GLOBAL !== "undefined" && GLOBAL || // more node.js
       typeof window !== "undefined" && window || // browsers
       this // either undefined or some global default?
    );
    

    Your going to have to hard code in feature detection for every environment.

提交回复
热议问题