This in classes and regular functions JS

Viewed 25

When we have an object and a method inside it, this refers to the object that it belongs to:

let myObj = {
  data: 'someData',
  test() {
    console.log(this);
  },
};

myObj.test();

here the result is : myObj

but what if my method is in a class with constructor?

export default class MovieCard extends React.Component {
  constructor(props) {
    super(props);
    this.state = { content: 'test' };
  }

  changer() {
    console.log(this);
  }
  render() {
    return null;
  }
}

It seems, in this case, this equals to 'undefined' why is that? is it because it has not been called yet?

1 Answers

It is a special case when your class is a React.Component. The this keywords in methods (except the constructor) of such classes is not automatically bound to the instance of the component.

A common solution is to add the following line to the constructor (for each method using this):

constructor(props) {
    // ...
    this.changer = this.changer.bind(this);
}

It makes sure that your methods have correctly bound this's.

For details of bind(): MDN Web Docs

Related