Eri*_*ard 10 javascript variables alert variable-assignment
我有一个HTML页面,附带以下JavaScript.
alert(box);
box = "Thinking outside the box";
Run Code Online (Sandbox Code Playgroud)
在控制台中我得到"Uncaught ReferenceError:box not defined"
当我把它改为:
alert(box);
var box = "Thinking outside the box";
Run Code Online (Sandbox Code Playgroud)
警报被调用并显示未定义.我需要能够解释这一点,我对于为什么会发生这种情况有一个模糊的概念.我知道当我使用var时,JavaScript在执行警报之前知道变量是否存在,但是没有必要为它分配值?我离开这里了吗?需要一些帮助来理解这一点
jfr*_*d00 11
当您使用变量定义变量时var,变量的声明将"悬挂"到范围的顶部,因此变量是针对整个范围定义的.变量的初始化(分配它的初始值)保持在代码中的相同位置.
因此,在您的第二个示例中,当您执行此操作时alert(box),由于box已提升的var语句,已声明该变量.你的第二个例子:
alert(box);
var box = "Thinking outside the box";
Run Code Online (Sandbox Code Playgroud)
基本上等同于此(box变量的声明被提升到范围的顶部):
var box;
alert(box);
box = "Thinking outside the box";
Run Code Online (Sandbox Code Playgroud)
这使得box变量在alert(box)语句之前被声明(虽然没有初始化),因此你得到的结果与声明的变量一致,但是没有值(alert()报告undefined是变量存在但尚未初始化的情况) ).
你的第一个例子没有使用var,因此没有提升,所以在你做的时候alert(box),根本就没有变量命名box,因此你得到了uncaught reference error.
这里有许多很多帖子描述了吊装的细节.你可以在这里看到一长串列表:https://stackoverflow.com/search?q = javascript+variable+hoisting,你会发现变量提升的进一步说明.
注意:函数声明也会被提升,所以你找到的一些帖子将是关于函数声明而不是变量声明,尽管这个概念几乎是一样的.