Reputation: 565
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 || {}))
Upvotes: 1
Views: 147
Reputation: 239653
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.
Upvotes: 1
Reputation: 782295
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.
Upvotes: 1