[英]Explanation Needed For A Javascript Hoisting Example
我正在研究一些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的不同行為
誰能解釋?
謝謝!
根據規格
讓clarifiedFunctionNames為空列表。
令clarifiedVarNames為空列表。
也
15.bi令bindingExists為varEnvRec.HasBinding(vn)。
這意味着JS引擎將首先提升功能聲明,並在遍歷變量聲明的同時檢查該變量是否已具有該名稱的綁定。
解釋如下
// 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)
隨其主體懸掛的函數聲明(按規范)。 因此,請在首次log
之前將function a
吊起。 然后,重新分配變量a
,第二個log
5。
因此,提升后,您的功能將變為以下內容:
var a;
a = function(){
console.log('In Console')
}
console.log(a)
a=5;
console.log(a)
// at this point a is a function, variable below has not yet been assigned.
// functions can be called from anywhere in the code file (not taking scope into account)
console.log(a)
// a is now assigned to a variable and assigned to 5, it no longer refers to the function
var a=5;
// function defined as a which can be called as a until a is reassigned
function a(){
console.log('In Console')
}
// a now refers to 5 at this point in the execution
console.log(a)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.