0

ES6 箭頭函式 (Arrow functions)

 3 years ago
source link: https://blog.niclin.tw/2019/09/30/arrow-function-in-javascript/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

很多人箭頭函式寫久了卻不清楚和一般 function 的差異在哪,大概能記得的就是簡潔好寫這樣。

不過還是有些細節要注意,寫法上也有可以縮寫的方式。

// 普通寫法
const currentLanguage = (user) => {
    return user.locale
}

// 縮寫,還幫你寫好 return
const currentLanguage = (user) => user.locale

// 一個參數時可以不加 () 括號
const currentLanguage = user => user.locale

// 沒參數時一定要有 () 括號
const currentLanguage = () => "zh-TW"

// 寫大括號時一定要有 return
const currentLanguage = user =>  { return user.locale }

值得注意的幾個點

  • this 是被綁定的,apply, call, bind 在 Arrow function 中是無法改變 this 的
  • 不能用在 constructor因為, this 是在物件下建立的
  • 沒有一般函式有的隱藏arguments物件。
  • 箭頭函式不能當作 generators 使用,使用yield會產生錯誤。

Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK