天天看點

【ES6】之 Arrow Function箭頭函數

基本文法

1. 更簡潔的代碼,擺脫function

[1, 2, 3].map(function(x) { return x * 2});

es6:

[1, 2, 3].map(x => x * 2);

2.語義化的this

在es6之前,函數都定義了自己的this值,這樣會帶來一些混亂

//在strict mode下

var self = this;

asyncFunction(function () {

  //callback 

  self.doSomething();

})

如果在es6下就不會有這個問題了,大大簡化了我們回調的時候的代碼:

asyncFunction(() => this.doSomething());

基本文法

1. (param1, param2, ..., paramN) => { statement }

例:

(x) => { console.log(x); }

2. (param1, param2, ..., paramN) => expression

等價于 (param1, param2, ..., paramN) => { return expression; }

例:

let sum = (x, y) => x + y;

sum(1, 2)

傳回值為3

3. 當隻有一個參數時,括号可以省略

(param) => { statement }

等價于 param => { statement }

例:

let double = x => x * 2;

double(3)

傳回值為6

4. 當沒有參數時,需要帶上括号

() => { statement }

說明

expression & statement

expression: expression evaluate to a value

statement: statement do something

參考資料

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions

https://hacks.mozilla.org/2015/06/es6-in-depth-arrow-functions/

strict mode VS non-strict mode

繼續閱讀