Defining an implementation independent version of the global object in JavaScript

前端 未结 3 1020
伪装坚强ぢ
伪装坚强ぢ 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 00:51

    this is in no way relevant to scope.

    (function(){
        (function(){
            (function(){
    
                (function(){
                alert( this ); //global object
                })()
    
            }).bind({})()
        }).apply({})
    }).call({})
    

    this is only resolved during the call time of the function and comes down to few simple rules.

    1. If the function is called as a property of some object, then that object will be this inside the function
    2. If the function is called as is, this will be undefined so under non strict mode it will be the global object
    3. If the function is called with .call/.apply then this is explicitly set by yourself.

    So as you can see, it would fall under rule #2, which resolves to undefined. And since there is no "use strict";:

    set the ThisBinding to the global object

    Edit: I have now ran some quick tests in RingoJS and they infact put the "global object" inside the actual global object (as defined by standards) which is ModuleScope. Just because the actual global object in most js implementations has Object and String and so on, doesn't make an object global if it has those objects under it as well. The reason you can access String and Object in RingoJS is because they put them into the ModuleScope prototype:

    var logs = require('ringo/logging').getLogger("h");
    
    logs.info( Object.getPrototypeOf( this ) === this.global );
    //true
    

    Further proof that ModuleScope is the actual global object:

    this.property = "value";
    logs.info( property );
    //"value"
    

    So nothing is gained from this kind of trickery, it doesn't fix anything:

    function injectGlobal(){
    globalProperty = "value"; // "use strict" would fix this!
    }
    
    injectGlobal()
    
    logs.info( globalProperty );
    //"value"
    

    Rant over, this refers to the actual global object already according to the rules given earlier in this post. this.global is not the real global object as defined by standards, it's just a container.

    Additionally you could emulate this behavior in browsers:

    Consider scopehack.js

    this.global = window.global || top.global || {};
    

    Consider main.html:

    
    
    
    
    

    And finally a "module" module.html:

    
    
    

    Which one is an actual global object in both module.html and main.html? It is still this.

    TLDR:

    var obj = {
    "String": String,
    "Object": Object,
    .....
    };
    

    Does not make obj the global object.

提交回复
热议问题