【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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值