Trying to wrap my head around Javascript scope and looking for someone to explain what's happening in the following. Hoping it'll help not just me...
var foo = {
bar: {}
};
(function(foo, bar) {
foo.bar = 'a';
bar = 'b';
}(foo, foo.bar))
console.log(foo.bar) // prints 'a', not 'b', how come?
You define two variables:
function(foo, bar)
You pass two values into them:
}(foo, foo.bar))
The value of foo
is a reference to an object (that object has a property bar
whose value is a reference to a different object)
The value of the variable bar
is a reference to that second object.
foo.bar = 'a';
You overwrite the bar
property of the first object with the string 'a'
. foo.bar
is no longer a reference to the second object. The value of bar
is still a reference to the second object.
bar = 'b';
You overwrite the local bar
variable with the string 'b'
. There are now no references to the second object left. The second object will be garbage collected.
console.log(foo.bar)
You output the value of the bar
property of the object that the value of foo
is a reference to. This is 'a'
since you modified the value of that property in the function.
foo
is an object, which is passed by reference. bar
is passed by value. When bar
is overwritten, it loses the relation to foo.bar
. Hence, foo.bar
is "a"`, which is what it was set to in the function.
var foo = {
bar: {}
};
(function(foo, bar) {
// foo is {bar:{}}
// bar is {}
foo.bar = 'a';
// now foo is {bar:'a'}
bar = 'b';
// now bar is 'b'
// bar has no relation to foo.bar anymore
}(foo, foo.bar))
console.log(foo.bar) // prints 'a', not 'b', how come?
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.