我正在研究一些 Javascript 提升概念并遇到了这个示例。
console.log(a)
var a=5;
function a(){
console.log('In Console')
}
console.log(a)
输出为
function a() {
console.log('In Console');
}
5
我不明白两个console.logs的不同行为
谁能解释一下吗?
谢谢!
最佳答案
根据 spec
Let declaredFunctionNames be an empty List.
Let declaredVarNames be an empty List.
还有
15.b.i Let bindingExists be varEnvRec.HasBinding(vn).
这意味着 JS 引擎将首先提升函数声明,并在迭代变量声明时检查该变量是否已具有绑定(bind)。
解释如下
// Before the following console statement function has been hoisted already and variable declaration is ignored.
console.log(a)
var a=5; // now the value of a is initialized.
//this statement has been hoisted above already
function a(){
console.log('In Console')
}
//value of a is 5 now
console.log(a)
关于javascript - Javascript 提升示例所需的解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36595173/