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

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

這兩個函數(箭頭函數與函數聲明)有什么區別

這兩個函數(箭頭函數與函數聲明)有什么區別

慕容森 2022-09-29 17:00:50
function pickColor() {    var random = Math.floor(Math.random() * colors.length);    return colors[random];}let pickColor = () => {    var random = Math.floor(Math.random() * colors.length);    return colors[random];}當我嘗試調用第二個時,我收到一個錯誤,顯示“初始化前無法訪問'pickColor'”
查看完整描述

3 回答

?
不負相思意

TA貢獻1777條經驗 獲得超10個贊

這是由于所謂的“吊裝”。


基本上,當您使用 時,JavaScript 會將函數移動到作用域的頂部,以便您可以在初始化之前訪問它。使用 let 不會這樣做。function


func_1();


function func_1() {

    console.log("Thing");

}



func_2(); // will cause an error


let func_2 = () => console.log("Thing");


細節:從技術上講,一切都是吊裝的,但是在你到達他們的生產線之前不要初始化。如果使用 ,則該變量的開頭為letconstvarundefined


console.log(aa); //undefined

var aa = "hello";

console.log(aa); //hello


console.log(bb) // error

let bb = "hello";


旁注(這部分不是上述問題的解決方案):1.你應該使用而不是,因為我不認為你需要改變函數的值。2.這些聲明之間的另一個區別是關鍵字的值(在這種情況下是相同的,但可以不同)。我不會在這里解釋它,如果你做更多的Javascript,你可能會遇到它,所以值得研究。constletthis


查看完整回答
反對 回復 2022-09-29
?
汪汪一只貓

TA貢獻1898條經驗 獲得超8個贊

let pickColor = ...行為類似于普通的變量聲明 + 賦值。


僅當執行實際的代碼行時,才會完成賦值。=


僅當調用發生在聲明之后且在可見范圍內時,才能調用以這種方式定義的函數。


相反,定義是完全“吊起”的,這意味著它們的行為就像在JS塊的頂部定義一樣,并且可以被稱為“在”它們的定義之前。function()


示例靈感來自 http://adripofjavascript.com/blog/drips/variable-and-function-hoisting.html:


isItHoisted();


function isItHoisted() {

    console.log("Yes! This function declaration acts the same as if it was declared _before_ the call.");

}



isThisOtherOneHoisted(); // throws an ReferenceError if used before it is  assigned 


let isThisOtherOneHoisted = () => console.log("Javascript sees that the name exists, but the assignment has not been done.");


/**

like :


There is this variable isThisOtherOneHoisted defined later, just so you know.

isThisOtherOneHoisted(); // error, variable does not even containt a function yet

isThisOtherOneHoisted = () => console.log(...)


*/

作為其他細節,javascript仍然“看到”它在初始化之前被使用,所以這就是為什么錯誤消息與你使用根本不存在的變量不同。

對于任何變量,僅針對變量存在的事實,都會提升聲明。的賦值僅在寫入的位置執行。=


查看完整回答
反對 回復 2022-09-29
?
Smart貓小萌

TA貢獻1911條經驗 獲得超7個贊

函數聲明


function pickColor(){...}

與使用 聲明的任何變量一起移動到作用域的頂部(首先提升)。var


其中,僅當解釋器遇到該行代碼時,才會訪問聲明的 as 函數表達式。let


示例 -


let two = () => {

  console.log('something else');

}


var x = 'demo'

let y = 'demo123'


function one() {

  console.log('something');  

};


function three(){

  one();  

}


變量 , 將一旦執行開始,就會移動到作用域的頂部,xfunction one(){...}function three(){...}


x,直到為該行分配值 。undefinedx = 'demo'x'demo'


變量未啟動或分配任何值,直到行y


let y = 'demo123'


因為 用于啟動變量,因此使用 啟動的函數表達式也是如此。letlet


查看完整回答
反對 回復 2022-09-29
  • 3 回答
  • 0 關注
  • 172 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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