iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 4
0
自我挑戰組

前端工程師的30份套餐系列 第 4

Day4-ES6 箭頭函式

最近剛踏入ES6的世界裡,常用箭頭函式卻不知道不是每種情況都適合使用,讓我們來仔細看看用法吧

箭頭函式

是ES6最受歡迎的一種新語法,原因是因為好處多且沒有什麼副作用或壞處。特性是Day3提到的寒式表達式(FE)的簡短寫法
(1)若沒有花括號{}就不用寫return,預設就有:

//傳統函式宣告
let eat = function(x,y) {
    return x+y;
}
//箭頭函式:             
let eat = (x,y) => (x+y);

(2)大括號的寫法

//傳統函式宣告
let eat = function(x,y) {
    return x+y;
}
//箭頭函式:             
let eat = (x,y) => {
    return x+y;
} 

(3)匿名涵式的寫法

//傳統方式
setTimeout(function(){
    console.log(過了一秒鐘");
},1000);

//箭頭凾式
setTimeout(() => {
    console.log(過了一秒鐘");
},1000);

綁定this值

箭頭函式可以取代ES5使用var self = this或 .bind(this)的情況,它可以綁定this變數。但有時情況較特殊,要視情況而定,而不是每種情況都可以用箭頭函式來取代。
原本的寫法:

const obj = {a:1}
function func(){
  const that = this

  setTimeout(
    function(){
      console.log(that)
    }, 2000)
}
func.call(obj) //Object {a: 1}

改用箭頭函式:

const obj = {a:1}
function func(){
  setTimeout( () => { console.log(this) }, 2000)
}
func.call(obj)  //Object {a: 1}

不可以使用箭頭函式的情況

  • call、apply、bind這三個方法,無法覆蓋箭頭函式中的this值。
  • 無法用於建構式(constructor),使用new會產生錯誤。

範例一

原始寫法:

var chocolate = {
  array: [1, 2, 3],
  sum :function  () {
    return this.array.reduce(function(result, item){return result + item})
  }
}
console.log(chocolate.aa()) //6

箭頭函式:
會以定義當下的this值為this值,也就式window物件,所以是存取不到物件中的this.array值。

const chocolate = {
  array: [1, 2, 3],
  sum: () => {
    return this.array.reduce((result, item) => result + item)
  }
}
chocolate.sum() //TypeError: Cannot read property 'array' of undefined

範例二:建構函式

const Message = (text) => {
  this.text = text;
}
// Throws "TypeError: Message is not a constructor"
const helloMessage = new Message('Hello World!');

上一篇
Day3-JavaScript 函式(function)
下一篇
Day5- JavaScript的this
系列文
前端工程師的30份套餐30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言