开发者

What is the mean of this? Engine bug or what? [duplicate]

This question already has answers here: Closed 12 years ago.

Possible Duplicate:

Javascript scoping variables theory

Hi all,

I want to ask something stranger. Here is the code.

var a = "defined";
function f() {
   alert(a);
   var a = 5;
}
f();

alerts "und开发者_运维知识库efined"

Can anyone explain that why I am getting "undefined".

Fatih..


That is called JavaScript Hoisting i suppose. Check out this video to learn more about it and solution to it:

http://net.tutsplus.com/tutorials/javascript-ajax/quick-tip-javascript-hoisting-explained/

To make it work, you will have to remove the var keyword form variable a:

var a = "defined";
function f() {
   alert(a);
   a = 5;
}
f();

So basically, it is a variable scope issue. The act of removing var keyword makes a variable globally available. Hence, there is no error raised this time.


In the function you get a new scope.

The var a in the function declares a local variable a, which masks the global one.

The assignment to a takes place later (after the alert), so until then a is undefined.

The confusing part is that it does not matter if you have the var a declaration on top or anywhere else in the function (can even be inside an if). The effect is the same: It declares a variable for that scope (effective even for code that is located before the declaration). That is why jslint recommends to declare all local variables on top.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜