es6之Arrow Function

本文系翻译文章,原文链接在此奉上Don’t Get Arrow Functions?

这篇文章主要向大家介绍何时以及如何使用es6的箭头函数。


1.一个quick example:


const addOne = function(n) {
    return n + 1;
}

使用箭头函数可以像这样:

const addOne = (n) => {
    return n + 1;
}

甚至更短可以像这样:

const addOne = (n) => n+1;

2.单个参数

如果函数中只有一个参数,那么可以这样:

// Turn this:
someCallBack((results) => {
    ...
})

// Into this:
someCallBack(results => {
    ...
})

但是如果没有参数,就不能省去()了

someCallBack(() => {
    ...
})

3.Callbacks

箭头函数对于回调函数是很有用处的,大多数情况下,我们防止this的指向的问题,采用如下方式

..
var _this = this;
someCallBack(function() {
    _this.accessOuterScope();
})

使用arrow functions,我们得到一个作用域块,并且‘this’还是‘this’,不再需要通过额外的变量改变this指向,代码如下:

someCallBack(() => {
    this.accessOuterScope();
})

4.The “Wrapper”

假如在react一个情境中,我们通过点击事件调用doSomething(),并且要传递一个参数,如id。
这个例子不会起效:

const User = React.createClass(function() {
  render: function() {
    return <div onClick={doSomething(this.props.id)}>Some User</div>
  }
})

当页面加载完后,会立即调用doSomething(),解决这个问题,使用如下方式:

const User = React.createClass(function() {

  render: function() {
    return <div onClick={this.onClick}>Some User</div>
  },

  onClick: function() {
    doSomething(this.props.userId);
  }

})

使用箭头函数,我们可以这样写

const User = React.createClass(function() {
  render: function() {
    return <div onClick={() => doSomething(this.props.userId)}>Some User</div>
  }
})

如果我们不使用箭头函数,使用bind()也可以达到同样效果,如下:

const User = React.createClass(function() {
  render: function() {
    return <div onClick={doSomething.bind(null, this.props.userId)}>Some User</div>
  }
})

不过确实使用箭头函数可以方便许多,而且不用考虑太多其他问题呢!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值