What does this.function = this.function.bind(this) do in the following context? ReactJS

Viewed 1262

I am following a tutorial series on udemy and the instructor hasn't really explained the following line of code:

this.getrandomnum = this.getrandomnum.bind(this);

So I am a bit confused as to what it does and was hoping to get some help. My code works with or without the above line.

Here is the full code:

class App extends Component {
  render() {
    return (
      <div className="App">
      <h1> Hello</h1>
      <Body />
      </div>
    );
  }
}

class Body extends Component{
  constructor(props){
    super(props);
    this.state = {};
    this.getRandomNumber = this.getRandomNumber.bind(this);
  }
  getRandomNumber(){
    console.log('some random number')
  }
  render(){
    return (
      <button onClick={this.getRandomNumber}>Random Number</button>
      )
  }
}
1 Answers
Related