That is called variable hoisting.
References:
- https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/var#var_hoisting
- http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting
- http://net.tutsplus.com/tutorials/javascript-ajax/quick-tip-javascript-hoisting-explained/
Variables (declared with var
) and functions are hoisted to the top of their scope.
So technically, your script is like this:
var a; // = undefined
var obj = { 'whichScope': a };
a = "After";
Although your first example doesn't do what you say. The value of obj.whichScope
is undefined
, as expected.
DEMO: http://jsfiddle.net/pRQwK/
As for your last statement, If whichScope refers to a function that returns 'a' then it does resolve to "After" in the second example.
- that is because the value of a
isn't captured (by a closure). When setting a property, its value is captured immediately (unrelated to a closure).