【发布时间】:2015-06-22 09:58:43
【问题描述】:
我不完全明白为什么以下显示“提升”到最后。
var x = 'set';
var y = function ()
{
// WHAT YOU DON'T SEE -> var x;
// is effectively "hoisted" to this line!
if (!x)
{
// You might expect the variable to be populated at this point...it is not
// though, so this block executes
var x = 'hoisted';
}
alert(x);
}
//... and this call causes an alert to display "hoisted"
y();
任何指针将不胜感激。
【问题讨论】:
-
它等同于
var y = function () { var x; ...,这使得x成为函数的本地并且未分配。如果块不会“停止”var提升 -
是的,
var x提升到作用域的顶部,这是 JS 中变量声明的正常行为。 -
@Qantas94Heavy:这个实际上可能成为变量提升的一个很好的规范副本,afaik 我们目前没有。仅适用于function hoisting...
-
@Bergi:是的,这似乎比我链接的问题更广泛。我会将另一个问题标记为与此问题重复。
标签: javascript hoisting