为什么我的变量没有被吊起?

时间:2012-10-11 16:30:06

标签: javascript hoisting

我有一个全局变量i我会增加(参见小提琴here):

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

i = 0;

在Chrome中,我收到错误Uncaught ReferenceError: i is not defined

变量i不应该在此处托管,因此在函数increment中,变量i被定义为undefined

1 个答案:

答案 0 :(得分:7)

悬挂变量声明声明。你没有声明。

声明语句使用var来声明变量。由于您尚未声明它,因此您只需要赋值表达式,它在表达式求值时隐式创建全局变量

换句话说,没有正式的声明意味着没有悬挂。


现在让我们说你做了正式声明它,允许变量声明被提升。 IIFE内部的操作将导致NaN,但稍后将分配0将覆盖。

这是因为仅提升声明,而不是作业

// 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
相关问题