ES2015入門系列3-箭頭函數

箭頭函數(Arrows), 是用新的 => 語法書寫的匿名函數, 如:javascript

[1, 2, 3].map(n => n + 1);

等同於下面使用ES5的寫法:java

[1, 2, 3].map(function(n) {
  return n + 1;
});

可能一開始沒法接受,但慢慢的會發現箭頭函數帶來的快感不言而喻。做爲一個PHP後端人士但願PHP也能支持該語法, ?。後端

  • 通常寫法, 如計算兩個數字之和, 並返回:函數

(arg1, arg2) => {
  let arg3 = arg1 + arg2
  return arg3
}

不用寫function關鍵字, 可是上面的寫法,也感受不出來有多少簡化,咱們來看看幾種狀況:this

  • 若是隻有一個參數,能夠不用寫括號code

n => {
  return n + 1
}

等價於ip

(n) => {
  return n + 1
}
  • 若是函數只有一行執行代碼,能夠省去花括號,寫在一行文檔

n => alert(n)

等價於io

n => {
  alert(n)
}
  • 寫在一行的時候,也能夠省略return關鍵字console

n => n + 1

等價於

n => {
  return n + 1
}
  • 沒有參數的時候,則必須用(), 如

() => alert('ES2015 Rocks!');

語法介紹完畢,須要特別強調並指出的是:

和用function關鍵字命名的函數不一樣的是,箭頭函數體內和它的所在的塊區域共享同一個this , 舉個例子:

直接在Chrome Console中運行如下代碼:

class Zoo {

  constructor(name, animals = []) {
    this.name = name;
    this.animals = animals;
  }

  list() {
    this.animals.map(animal => {
      console.log(this.name + '裏有' + animal);
    });
  }

  list2() {
    this.animals.map(function() {
      console.log(this.name + '裏有' + animal);
    });
  }

}

let zoo = new Zoo('小紅山動物園', ['大象', '猴子', '長頸鹿']);

zoo.list();
zoo.list2();

以上代碼輸出:

> 小紅山動物園裏有大象
> 小紅山動物園裏有猴子
> 小紅山動物園裏有長頸鹿
> Uncaught TypeError: Cannot read property 'name' of undefined(…)

這就是文檔中所說的:

Unlike functions, arrows share the same lexical this as their surrounding code.

相信你也已經掌握箭頭函數的用法了吧?歡迎繼續瀏覽下一章節。

相關文章
相關標籤/搜索