What happens if I don't use this when referencing a method from inside a class?

Question

What happens if I don’t use this when referencing a method from inside a class?

Answer

When calling or referencing a method that’s defined on a class from inside another method on the same class, we need to use this to tell our method where to find the method we’re trying to call/reference. If we do not use this, our method will look for the method name (we’re referencing/calling) within the scope of it’s own definition and won’t be able to find it!

For example:

import React from 'react';
import ReactDOM from 'react-dom';

class NounGreeting extends React.Component {
  noun() {
    return 'Dog';
  }

  render() {
    return <h1>Hello {this.noun()}.</h1>; //here `this` is refrring to the `noun` method defined on our `NounGreeting` class
  }
}

ReactDOM.render(<NounGreeting />, document.getElementById('app'));

vs.:

import React from 'react';
import ReactDOM from 'react-dom';

class NounGreeting extends React.Component {
  noun() {
    return 'Dog';
  }

  render() {
    return <h1>Hello {noun()}.</h1>; //here we would run into an error `'noun' is not defined` - this is because our `render` method is looking inside the scope of it's own definition for the `noun` method
  }
}

ReactDOM.render(<NounGreeting />, document.getElementById('app'));
10 Likes