我发现了以下关于 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()。但它说未定义,函数 bar()。
console.log(foo);
console.log(bar);
var foo = 8;
function bar() {
console.log("bar");
}