您的位置:首页 > Web前端 > JavaScript

【ES6】之 Arrow Function箭头函数

2016-03-29 18:21 836 查看
基本语法

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息