Search code examples
reactjsecmascript-6es6-promise

React / ES6 - Why calling a function inside another only works with es6 arrow functions?


I have a question about es6 arrow functions for promises (in my example in react). In my sample code, I simply want to call a function insight another function. It only works if I use es6. I've been reading online but I don't exactly understand why it only works with es6.

class App extends React.Component {
constructor(props) {
    super(props);
    this.state = {
    }
    this.handleInput = this.handleInput.bind(this);
    this.testing = this.testing.bind(this);
}

testing(){
console.log("hello")
}

handleInput(){
    ...
.then(function(){
    this.test() //doesnt work
    test() //doesnt work
})
.then => res{
// I actually don't require parameters, but it's
// never working unless I use this syntax
.this.test() // WORKS
}
}

  render() {
    return (
      <div>
        Hello {this.props.name}
      </div>
    );
  }
}

Solution

  • Because you are loosing the context for native functions.

    Let me explain. If you r calling func like 'this.test()' for 'function test()' you call it from the current call context. So the 'this' keyword would contain the context environment of the function-caller. Arrow functions, for the flip side, always match the context to the object, or function, where they have been created.