I have a global variable i which I increment (see fiddle here):

(function increment() {
   i += 1;   
})();

i = 0;

​In Chrome, I get the error Uncaught ReferenceError: i is not defined.

Shouldn't the variable i be hosted here, so that inside the function increment, the variable i is defined as undefined?

有帮助吗?

解决方案

Variable declaration statements are hoisted. You have no declaration.

A declaration statement uses var to declare the variable. Since you haven't declared it, all you have is the assignment expression, which implicitly creates the global variable at the time of the expression evaluation.

In other words, no formal declaration means no hoisting.


Now let's say you did formally declare it, allowing the variable declaration to be hoisted. The operation inside the IIFE would result in NaN, but would be overwritten by the later assignment of 0.

This is because only the declaration is hoisted, not the assignment.

// The 'var i' part below is actually happening up here.

(function increment() {
   i += 1;   // "i" is declared, but not assigned. Result is NaN
})();

var i = 0; // declaration was hoisted, but the assignment still happens here

console.log(i); // 0
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top