Proteeti Prova
Proteeti Prova

Reputation: 1169

"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?

Upvotes: 5

Views: 580

Answers (1)

Scott Rudiger
Scott Rudiger

Reputation: 1300

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.

Upvotes: 9

Related Questions