2 回答

TA貢獻1830條經驗 獲得超3個贊
發生這種情況是因為 JavaScript 與提升的工作方式有關。函數function VARIABLENAME() {}會在變量的“存在”調用下調出,并且變量更改值保留在其位置,但由于函數向上移動而相對向下移動。
第一組
(() => {
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貢獻1829條經驗 獲得超6個贊
提升是在編譯期間將變量(僅聲明的左側)或函數聲明移動到相應環境頂部的行為。
Javascript 引擎在代碼執行之前的創建階段為變量和函數分配內存。
您的第一個示例的解釋就像您編寫的那樣:
// 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
您的第二個示例的解釋與您編寫的略有不同:
// 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
需要了解的一件有趣的事情是: 如果您像這樣編寫第一個示例......
var x
(function x() {}) // round brackets
console.log(x)
...函數聲明的提升不會發生,因為引擎看到的第一件事既不是 var 也不是函數!
添加回答
舉報