Friday, 15 March 2013

Javascript: Understanding variables wrapped in functions -



Javascript: Understanding variables wrapped in functions -

trying wrap head around javascript scope , looking explain what's happening in following. hoping it'll help not 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 2 variables:

function(foo, bar)

you pass 2 values them:

}(foo, foo.bar))

the value of foo reference object (that object has property bar value reference different object)

the value of variable bar reference sec object.

foo.bar = 'a';

you overwrite bar property of first object string 'a'. foo.bar no longer reference sec object. value of bar still reference sec object.

bar = 'b';

you overwrite local bar variable string 'b'. there no references sec object left. sec object garbage collected.

console.log(foo.bar)

you output value of bar property of object value of foo reference to. 'a' since modified value of property in function.

javascript

No comments:

Post a Comment