Why in some cases it's necessary to bind a method to `this` and in some others it’s not?

Hi everyone, my question is about this exercise in which a component class has the method componentDidMount() that calls this:

componentDidMount() {
    // Paste your code here.
    const oneSecond = 1000;
    setInterval(() => {
      this.setState({date: new Date()
      });
    }, oneSecond);
  }

Even though we don’t bind the method to this in the constructor, the code still works. Which I think goes against what has been stressed in a previous exercice and therefore gets me confused.

A similar case can be found in this exercise where we don’t bind startInterval() to this but the code still works as well:

export class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = { date: new Date() };
  }

  startInterval() {
    const delay = this.props.isPrecise ? 100 : 1000;
    this.intervalID = setInterval(() => {
      this.setState({ date: new Date() });
    }, delay);
  }

My question:
Why in some cases it is necessary to bind a method to this and in some others it’s not?

Hi, in the exercise you are referring to:

class Example extends React.Component {
  constructor(props) {
    super(props);
    this.state = { weather: 'sunny' };
    this.makeSomeFog = this.makeSomeFog.bind(this);
  }
 
  makeSomeFog() {
    this.setState({
      weather: 'foggy'
    });
  }
}

makeSomeFog is a class method, and class methods in JavaScript are not bound by default, so “this” returns undefined.
And in other two examples setInterval method is used, which is not a class method, but a method offered on the Window interface.

“this” keyword is a tricky and complicated topic. You can read more about it in general here: this - JavaScript | MDN
And in React docs: https://reactjs.org/docs/handling-events.html

2 Likes