简体   繁体   中英

JavaScript: Initializing inner variable after initializing object

Update: rewriting question because original question had false assumptions (I was running code in a console that had already initialized the variables I thought were undefined).

This makes sense:

var obj = { 'whichScope': a };
obj.whichScope; //"ReferenceError: a is not defined"

But then how come this next example doesn't throw an error? And if the second line is getting run before the first line, why doesn't obj.whichScope resolve to "After"?

var obj = { 'whichScope': a };
var a = "After";
obj.whichScope; //"undefined"

If "var a" in the previous example runs before obj is initialized, does any part of 'a = "After";' also run before obj is initialized?

var a = "Before";
var obj = { 'whichScope': a };
a = "After";
obj.whichScope; //"Before"

If whichScope refers to a function that returns 'a' then it does resolve to "After" in the last example.

That is called variable hoisting.

References:

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).

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM