Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"this" keyword with multiple objects

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?

like image 310
Proteeti Prova Avatar asked Mar 04 '19 02:03

Proteeti Prova


People also ask

What is this () in Java?

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.

How does the this keyword work?

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.

Can you use multiple objects for the same class?

No, it's fine. Just create an array (or List ) of Player and extract the code of Player creation in a separate method.


1 Answers

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.

like image 162
Scott Rudiger Avatar answered Oct 07 '22 09:10

Scott Rudiger