简体   繁体   中英

Passing values to global variables

Does someone has a plausible explanation why javascript does not the pass the object literal as a value to the global variable that is passed via function parameter?

Do I overlook some fundamental rules?

(function(global) {
    var id = "3543a1354";
    global = {
        name: 'global',
        getId: function() {
            return id;
        }
    };
})(this.global = this.global || {})

So essentially the value of the parameter 'global' after executing the code is an empty object. Very strange: if setting a breakpoint for example on the last line and execute the object literal assignment in the console, then the value is correctly passed to 'global'.

BTW this would work as expected:

(function(global) {
    var id = "3543a1354";
    global.name = "global";
    global.getId = function() {
        return id;
    }
}(this.global = this.global || {}))

In both functions, global is a local variable, because it's a function parameter.

In the first case, you're creating a new object with the literal notation, and assigning this to the local variable. This has no effect on the variable that was used in the function call.

In the second case, you're modifying the properties of the object that the local variable refers to. This is the same object that the variable used in the function call refers to, so it's visible to the caller.

You are passing this.global to the function and inside the function global is the parameter which refers to the global global .

When you say,

global = {...}

you are now changing what global refers to. Since you have changed the reference, the global global is left unchanged and the local global refers to the newly assigned object.

In the second case,

global.name = "global";
global.getId = function () {..}

you are altering the local global object, which actually refers to the global global . So, you are indirectly changing global global . That is why, this mutates the global global and the first one didn't.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM