I understand that "this" keyword refers to the currrent/immediate object. While watching a React.js tutorial, I saw the instructor using the keyword with multiple objects. The code looks like this:
class Counter extends Component {
state = {
count: 0
};
styles = {
fontSize: 10
};
render() {
return (
<div>
<h1 style={this.styles}>Hello</h1>
<span>{this.formatCount()}</span>
</div>
);
}
formatCount() {
const { count } = this.state;
return count === 0 ? "Zero" : count;
}
}
Inside formatCount(), why we are referring to this.state
instead of state.count
? Also, why not formatCount()
instead of this.formatCount()
? The instructor keeps saying this
refers to the current object, but he is writing this.objectname.properties
everytime. Why is that? Can't I distinguish the objects only with the objectname?
The this is a keyword in Java which is used as a reference to the object of the current class, with in an instance method or a constructor. Using this you can refer the members of a class such as constructors, variables and methods.
In JavaScript, the this keyword refers to an object. Which object depends on how this is being invoked (used or called). The this keyword refers to different objects depending on how it is used: In an object method, this refers to the object.
No, it's fine. Just create an array (or List ) of Player and extract the code of Player creation in a separate method.
Your instructor is using public field declarations within the class.
If it helps your understanding, the equivalent code without this feature would be:
class Counter extends Component {
constructor() {
this.state = {
count: 0
};
this.styles = {
fontSize: 10
};
}
render() {
return (
<div>
<h1 style={this.styles}>Hello</h1>
<span>{this.formatCount()}</span>
</div>
);
}
formatCount() {
const { count } = this.state;
return count === 0 ? "Zero" : count;
}
}
In other words, state = {...}
and styles = {...}
are just a shorthand for declaring this.state
and this.styles
in the constructor method.
Edit: In case you'd like to better understand the this
keyword, here's another question you can reference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With