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'));
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.
It depends on what you want to do, you don’t have to use getters but if you want you can.
You should learn as many tools as you can, so when you need to do something you can easily find the right tool.
If you use onClick={function()}, it will immediately call the function upon rendering. You want to pass the function, not call it, so that it only calls when the click event happens.