es6之Arrow Function

来源:互联网 发布:mac移除应用程序 编辑:程序博客网 时间:2024/04/29 20:46

本文系翻译文章,原文链接在此奉上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>  }})

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

0 0