2 回答

TA貢獻(xiàn)1830條經(jīng)驗(yàn) 獲得超3個(gè)贊
發(fā)生這種情況是因?yàn)?JavaScript 與提升的工作方式有關(guān)。函數(shù)function VARIABLENAME() {}會(huì)在變量的“存在”調(diào)用下調(diào)出,并且變量更改值保留在其位置,但由于函數(shù)向上移動(dòng)而相對(duì)向下移動(dòng)。
第一組
(() => {
var x
function x() {}
console.log(x)
})()
// This gets converted to:
(() => {
var x // This variable exists
x = function x() {} // Ya know that variable called x? well its a function
console.log(x)
})()
第二組
(() => {
var x = 1
function x() {}
console.log(x)
})()
// This gets converted to:
(() => {
var x // the variable x exists
x = function x() {} // Functions are moved to the top, under variable declarations
x = 1 // x is now the value 1
console.log(x)
})()

TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超6個(gè)贊
提升是在編譯期間將變量(僅聲明的左側(cè))或函數(shù)聲明移動(dòng)到相應(yīng)環(huán)境頂部的行為。
Javascript 引擎在代碼執(zhí)行之前的創(chuàng)建階段為變量和函數(shù)分配內(nèi)存。
您的第一個(gè)示例的解釋就像您編寫的那樣:
// creation phase start
var x = undefined;
function x() {}; // a function is fully hoisted. So x references the function.
// creation phase end
// execution phase start
console.log(x); // therefore x is a function
// execution phase end
您的第二個(gè)示例的解釋與您編寫的略有不同:
// creation phase start
var x = undefined;
function x() {}
// creation phase end
// execution phase start
x = 1;
console.log(x); // therefore x got overwritten, therefore 1
// execution phase end
需要了解的一件有趣的事情是: 如果您像這樣編寫第一個(gè)示例......
var x
(function x() {}) // round brackets
console.log(x)
...函數(shù)聲明的提升不會(huì)發(fā)生,因?yàn)橐婵吹降牡谝患录炔皇?var 也不是函數(shù)!
添加回答
舉報(bào)