【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

你可能感兴趣的:(javascript,es6)