Sunday, 10 October 2021

JavaScript bind() method

  • we invoke the bind() on a functon
  • the argument passed into bind() is an object
  • it will return a new function. This new function becomes method of that object
class NameForm extends React.Component {
  constructor(props) {
    super(props);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.input = React.createRef();
  }
  
   handleSubmit(event) {
    alert('A name was submitted: ' + this.input.current.value);
    event.preventDefault();
  }
  
 .....

 

For the above code, we need bind this. Because when we set this.handleSumit as callback of event handler, this inside that function is lost

onSubmit={this.handleSubmit}

However, we also can use arrow function for event handler. arrow function binds this lexically, so this will point to NameForm

onSubmit={()=>this.handleSubmit()}

For Promise then callback, we also need to write it as arrow function to access this of class instance.

A blog about why we need bind this

No comments:

Post a Comment