【发布时间】:2015-09-18 06:35:18
【问题描述】:
我看到了以下关于 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();
但是,我无法理解摘要中第三点的含义。谁能解释第三点?第三点是什么意思?
根据第三点的解释,下面的sn -p应该返回8,函数bar()。但它说未定义,函数 bar()。
console.log(foo);
console.log(bar);
var foo = 8;
function bar() {
console.log("bar");
}
【问题讨论】:
-
在您的情况下,第 3 点意味着变量赋值语句
var foo将在您的function bar()被提升之前被提升。所以实际上你的解释代码是var foo; function bar(),如果你没有赋值语句,它会是function bar(); var foo -
foo = 8;不是变量赋值,var foo;是变量声明部分吗? -
你能解释一下为什么会这样吗?我认为函数具有优先权是有含义的,因为它们可能会被使用。
-
@AdityaParab 这是否意味着它也适用于函数表达式?因为它也有任务。
-
我不知道为什么这个规则是由 JS 引擎实现的。我只是根据我开发 js 代码的经验做出一个疯狂的猜测。在一个易于维护的代码中,鼓励开发人员向外界公开方法——而不是变量。而且由于这是我们公开的方法,我们不能在外面得到
undefined。 :) 我真诚地相信这就是为什么函数优先于未初始化的变量的原因。
标签: javascript hoisting