这个ES6箭头功能和常规功能之间的区别?

hid*_*ace 3 javascript ecmascript-6 reactjs

对于ES6来说仍然是新手,所以试图理解为什么下面这两个函数之间存在差异.我在React工作,并注意到我在编写设置状态的非ES6函数时遇到错误.这发生在componentDidMount中.

这种方式在ES6中工作并返回我需要的东西:

(pos) => this.setState({
    lat: pos.coords.latitude,
    lng: pos.coords.longitude,
  })
Run Code Online (Sandbox Code Playgroud)

但是,以这种方式抛出一个错误 - "Uncaught TypeError:this.setState不是一个函数"

 function(pos) {
    this.setState({
      lat: pos.coords.latitude,
      lng: pos.coords.longitude
    })
  }
Run Code Online (Sandbox Code Playgroud)

这些不完全相同吗?任何人都可以解释为什么会抛出这个错误?

以下是来自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>
    );
  }
});
Run Code Online (Sandbox Code Playgroud)

任何和所有的帮助表示赞赏.谢谢!

Que*_*Roy 7

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

(x) => this.stuff = x
Run Code Online (Sandbox Code Playgroud)

(大部分)相当于:

(function(x) {
    return this.stuff = x;
}.bind(this))
Run Code Online (Sandbox Code Playgroud)

箭头功能也将保留arguments,supernew.target在其内部创建它的功能.

意思是

(function a() {
  const u = () => console.log(arguments);
  u("whatever");
})("a args");
Run Code Online (Sandbox Code Playgroud)

会印出类似的东西["a args"].

有关更多信息,请参见此处