The problem is that, whether you realise it or not, javascript invisibly moves all the var declarations to the top of the function scope.
so if you have a function like this
var i = 5;
function testvar () {
alert(i);
var i=3;
}
testvar();
the alert window will contain undefined. because internally, it's been changed into this:
var i = 5;
function testvar () {
var i;
alert(i);
i=3;
}
testvar();
this is called "hoisting".
The reason crockford so strongly advocates var declarations go at the top, is that it makes the code visibly match what it's going to do, instead of allowing invisible and unexpected behavior to occur.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…