Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Understanding variables wrapped in functions

Tags:

javascript

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? 
like image 530
Lane Avatar asked Apr 20 '26 01:04

Lane


2 Answers

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.

like image 200
Quentin Avatar answered Apr 22 '26 15:04

Quentin


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? 
like image 35
Scimonster Avatar answered Apr 22 '26 13:04

Scimonster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!