Possible Duplicate:
Redeclare JavaScript Variable

I have the next piece of code:

var i = 11;
alert(i);
function a(){
    alert(i);
    var i = 2;
    alert(i);
}
a()

The second alert(i) (inside the function) produces undefined. I'm guessing it has to do with the way JS engine runs through the code - maybe it doesn't store variables first, before going throught the lines?

Anyway I thought that this is not a problem is JS because it supports hoisting. I probably got it wrong - does anybody care to explain?

Thanks!

有帮助吗?

解决方案

JavaScript does indeed hoist declarations to the top of the scope in which they occur, but assignments happen at the place you would expect them to. Your code is effectively parsed like this:

/* Function declarations are hoisted first, which is why you can invoke a
   function before it appears to be defined in the source */
function a() {
    var i; // Declaration is hoisted (this i shadows the outer i)
    alert(i);
    i = 2; // Assignment to local i happens in place
    alert(i);
}
var i; // Declaration is hoisted (at this point, i === undefined)
i = 11; // Assignment happens in place
alert(i);
a();

This is detailed in the spec. Upon entering a new execution context, the following happens:

For each VariableDeclaration and VariableDeclarationNoIn d in code, in source text order do

  • Let dn be the Identifier in d.
  • Let varAlreadyDeclared be the result of calling env’s HasBinding concrete method passing dn as the argument.
  • If varAlreadyDeclared is false, then
    • Call env’s CreateMutableBinding concrete method passing dn and configurableBindings as the arguments.
    • Call env’s SetMutableBinding concrete method passing dn, undefined, and strict as the arguments.
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top