Changing JavaScript's global object?

后端 未结 3 672
猫巷女王i
猫巷女王i 2021-01-02 14:00

Is there a way to change the root object in JavaScript?

For example, in browsers, the root object is \"window\". So

X = 5;
console         


        
3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-02 14:37

    If you're talking about variables, JavasScript has function scope.

    X = 5;  // global variable
    
    console.log( window.X );  // 5
    
    (function() {
       var X = 6;  // declare a local variable by using the "var" keyword
    
       console.log( X );  // 6
    })();
    
    console.log( window.X );  // 5
    

    Otherwise, you can create an Object, and add properties to it.

    X = 5; 
    
    console.log( window.X );  // 5
    
    var obj = {};
    
    obj.X = 6;
    
    console.log( obj.X ); // 6
    
    console.log( window.X );  // 5
    

    EDIT: Adding another possible solution that could be used.

    You could invoke an anonymous function, but set the context of the function to your X object. Then this in the function will refer to X.

    var X = {};
    (function(){
        this.A = 5;
        this.B = 8;
        this.C = 7;
    }).call(X);
    for(a in X){
        console.log(a+" is "+X[a]);
    }
    

    The .call() method (as well as the .apply() method) allow you to explicitly set the thisArgof a calling context. The first argument you pass will be howthis` is defined in the context of the invocation.

    Or just pass X in as an argument.

    var X = {};
    (function(X){
        X.A = 5;
        X.B = 8;
        X.C = 7;
    })(X);
    for(a in X){
        console.log(a+" is "+X[a]);
    }
    

    Though the simplest is to simply reference it (as I noted in my answer above).

    var X = {};
    X.A = 5;
    X.B = 8;
    X.C = 7;
    for(a in X){
        console.log(a+" is "+X[a]);
    }
    

    or use a module pattern:

       /****** I'm guessing at the use of "global" here ********/
    global.myNamespace = (function(global,undefined) {
    
        // define the object to be returned
        var X = {};
    
        //  define private local variables
        var a_local = 'some value';
        var another_local = 'some other value';
    
        // define private functions
        function myFunc() {
            // do something with local variables
        }
    
        // give the return object public members
        X.someProperty = 'some value';
        X.anotherProperty = 'another value';
        X.publicFunc = function() {
            //do something with the local variables
            //    or public properties
        };
        X.anotherFunc = function() {
            //do something with the local variables
            //    or public properties
        };
        // return the object
        return X;
    
    })(global);
    
    console.log(myNamespace);
    

提交回复
热议问题