Javascript: understanding variables included in functions
Trying to wrap my head around the Javascript area and find someone to explain what's going on in the following. Hope this helps more than 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?
source to share
You are defining two variables:
function(foo, bar)
You are passing two values ββto them:
}(foo, foo.bar))
The value foo
is a reference to an object (this object has a property bar
whose value is a reference to another object)
The value of the variable bar
is a reference to this second object.
foo.bar = 'a';
You are replacing the property of the bar
first object with a string 'a'
. foo.bar
is no longer a reference to the second object. The value bar
is still a reference to the second object.
bar = 'b';
You are replacing the local variable bar
with a string 'b'
. There are currently no references to the second object from the left. The second object will collect garbage.
console.log(foo.bar)
You are outputting the value of the property of the bar
object that the value refers to foo
. This 'a'
is since you changed the value of this property in the function.
source to share
foo
is an object that is passed by reference. bar
passed by value. When bar
overwritten, it loses relevance to foo.bar
. Therefore, foo.bar
- this is "a", which was set 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?
source to share