亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

用 var 提升

用 var 提升

鴻蒙傳說 2023-07-20 15:11:12
為什么在第一種情況下會打印 x 是一個函數而不是未定義?(() => {    var x    function x() {}    console.log(x)})()> ? x() {}(() => {    var x = 1    function x() {}    console.log(x)})()> 1
查看完整描述

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)

})()


查看完整回答
反對 回復 2023-07-20
?
肥皂起泡泡

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 也不是函數!


查看完整回答
反對 回復 2023-07-20
  • 2 回答
  • 0 關注
  • 153 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號