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

didn’t the lesson teach that we don’t use () on get method calls within the class component?

3 Likes

lol. True that. The answer does not use “get” in front of method definition either.

1 Like

This is the first time I’ve understood what the this keyword is doing, thanks for the clear explanation.

Would be interested to know why you’ve not used the get method in your example though?

It’s not a typo, she called a method not a get method.

I understand. The course teaches to use get method for something like this and the q&a does not use the get method, hence confusing within the context.

I don’t really think that the course stipulates the use of the ‘get’ keyword.

In fact, I really appreciate the fact that she omitted the get in her example, a silent reminder that we do not use parens with getter functions, and we use them when they are not so.

10-4. And in full agreement with that statement.