【问题标题】:Difference between this ES6 arrow function and regular function? [duplicate]这个 ES6 箭头函数和常规函数的区别? [复制]
【发布时间】:2015-09-04 13:43:00
【问题描述】:

对 ES6 还是新手,所以试图理解为什么下面这两个函数之间存在差异。我正在使用 React 并注意到在编写设置状态的非 ES6 函数时出现错误。这发生在 componentDidMount 中。

这种方式在 ES6 中有效并返回我需要的内容:

(pos) => this.setState({
    lat: pos.coords.latitude,
    lng: pos.coords.longitude,
  })

但是,这样会抛出一个错误——“Uncaught TypeError: this.setState is not a function”

 function(pos) {
    this.setState({
      lat: pos.coords.latitude,
      lng: pos.coords.longitude
    })
  }

这些不完全一样吗?谁能解释为什么会抛出这个错误?

这是来自 react 类的代码,用于提供更多上下文:

var GeolocationExample = React.createClass({
  getInitialState: function() {
    return {
      lat: '',
      lng: '',
    };
  },

  componentDidMount: function() {
    navigator.geolocation.getCurrentPosition(

      // Where I'm placing each of the above mentioned functions,

      (err) => alert(err.message),
    );
  },

  render: function() {
    return (
      <View>
        <Text>
          <Text style={styles.title}>Initial position: </Text>
          {this.state.lat}
        </Text>
        <Text>
          <Text style={styles.title}>Current position: </Text>
          {this.state.lng}
        </Text>
      </View>
    );
  }
});

我们不胜感激。谢谢!

【问题讨论】:

  • 正如@Andrey 指出的那样:Arrow functions have implicit this binding 所以带有(function(pos){...}).bind(this) 的非箭头应该等同于箭头一

标签: javascript reactjs ecmascript-6


【解决方案1】:

不,它们不一样。箭头函数会自动绑定到创建它们的上下文。 这意味着

(x) => this.stuff = x

(大部分)等同于:

(function(x) {
    return this.stuff = x;
}.bind(this))

箭头函数还将保留创建它的函数的argumentssupernew.target

这意味着

(function a() {
  const u = () => console.log(arguments);
  u("whatever");
})("a args");

将打印类似["a args"] 的内容。

更多信息请参见here

【讨论】:

  • 感谢您的清晰解释 - 非常感谢!
  • 还有更多内容,但这是一个很好的介绍。 argumentssupernew.target 在箭头函数中工作。当尚未初始化 this 时,也可以创建箭头函数,例如在调用 super() 之前的类构造函数中。
  • 哦,这是对的。更准确地说,就像this 一样,它们从创建它们的函数中保留这些值。我其实不知道这一点。谢谢。
【解决方案2】:

词汇 this

直到箭头函数,每个新函数都定义了自己的 this 值 (构造函数中的新对象,在严格模式下未定义 函数调用,如果函数被调用为上下文对象 “对象方法”等)。事实证明这很烦人 面向对象的编程风格。

发件人:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

这就是为什么,当你写的时候:

 this.setState = function() {};
 function(pos) {
    this.setState({
      lat: pos.coords.latitude,
      lng: pos.coords.longitude
    })
  }

函数内部this.setState中的this设置为{}(一个空对象)。

当您改用=&gt; 表示法编写它时,this 与函数外部共享,相当于:

 this.setState = function() {};
 var self = this;
 function(pos) {
    self.setState({
      lat: pos.coords.latitude,
      lng: pos.coords.longitude
    })
  }

或者你也可以使用function(pos){ /* Stuff here */ }.bind(this);

【讨论】:

  • 谢谢 - 非常有帮助!
  • "事实证明这对于面向对象的编程风格很烦人" - 等一下?没有this,面向对象编程几乎不可能实现!
  • 否,setState 中的this 未设置为{}。你从哪里得到的?
  • 在我的回答中查看链接
  • 这是错误的。这取决于如何调用您的匿名函数。在这里,它似乎根本没有被调用(因为它是匿名的,所以很可能永远不会被调用)。
猜你喜欢
  • 2017-02-05
  • 2016-01-25
  • 1970-01-01
  • 2018-08-01
  • 2018-08-02
  • 2018-07-18
  • 2016-03-25
  • 1970-01-01
相关资源
最近更新 更多