我看到了一篇关于JavaScript变量提升的文章。这篇文章总结了以下三点:
1. All declarations, both functions and variables, are hoisted to the top of the containing scope, before any part of your code is executed.
2. Functions are hoisted first, and then variables.
3. Function declarations have priority over variable declarations, but not over variable assignments.
var showState = function() {
console.log("Idle");
};
function showState() {
console.log("Ready");
}
showState();
我理解到代码会被JavaScript引擎解释为:
function showState() { // moved to the top (function declaration)
console.log("Ready");
}
var showState; // moved to the top (variable declaration)
showState = function() { // left in place (variable assignment)
console.log("Idle");
};
showState();
但是,我无法理解摘要中的第三点的含义。有人能解释一下第三点吗?第三点的含义是什么?
根据第三点的解释,以下代码片段应该返回8,函数bar()。但它显示为undefined,函数bar()。
console.log(foo);
console.log(bar);
var foo = 8;
function bar() {
console.log("bar");
}
var foo
将会在您的function bar()
被提升之前被提升。所以实际上您的代码会被解释为var foo; function bar()
,如果没有赋值语句,它将是function bar(); var foo
。 - AdityaParabfoo = 8;
不是变量声明,而是变量赋值。var foo;
才是变量声明的部分。 - nilsundefined
。 :) 我真诚地相信这就是函数优先于未初始化变量的原因。 - AdityaParab