下面js運行結(jié)果是?
var a
if(true){
a = 5
function a(){}
a = 0
console.log(a)
}
console.log(a)
//運行結(jié)果
// 0
// 5
要是對答案困惑可以參考這個解釋: https://stackoverflow.com/questions/58619924/confused-about-function-declaration-in/58620404#58620404
更底層的原理可以參考 ES6中塊級作用域中函數(shù)的語義:https://stackoverflow.com/questions/31419897/what-are-the-precise-semantics-of-block-level-functions-in-es6
參考中這樣說的:
The following happens:
(1) There exist two variable declarations a, one inside the block and one outside of it. //存在兩個變量聲明a驰坊,一個在塊內(nèi)部匾二,一個在塊外部。
(2) The function declaration gets hoisted, and bound to the inner blocks variable. //函數(shù)聲明被提升拳芙,并綁定到內(nèi)部塊變量舟扎。
(3) a = 5 is reached, which overrides the block variable. //a=5譬猫,覆蓋內(nèi)部塊變量删窒。
(4) the function declaration is reached, and the block variable is copied to the outer variable. Both are 5 now. //函數(shù)聲明,內(nèi)部塊變量復(fù)制到外部變量特碳。他們現(xiàn)在是5了。
(5) a = 0 is reached, which overrides the block variable. The outer variable is not affected by this. //a=0益愈,覆蓋內(nèi)部塊變量敏释。外部變量不受此影響。
var a1;
if (true) {
function a2() {} // hoisted
a2 = 5;
a1 = a2; // at the location of the declaration, the variable leaves the block
a2 = 0;
console.log(a2)
}
console.log(a1);
This is actually not really part of the specification, it is part of the web legacy compatibility semantics, so don't declare functions inside blocks and don't rely on this code to behave in this way.
This is also explained here
這實際上并不是規(guī)范的一部分蜂大,它是web遺留兼容性語義的一部分,所以不要在塊內(nèi)聲明函數(shù)财喳,也不要依賴此代碼以這種方式運行耳高。
這里也解釋了這一點