5

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?

Proteeti Prova
  • 777
  • 1
  • 13
  • 40

1 Answers1

9

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.

Scott Rudiger
  • 1,045
  • 9
  • 16
  • 1
    To complete the answer, please mention that const { count } = this.state is just a shorthand for const count = this.state.count, OP was unlucky to see it for the first time while still learning about the "this" keyword and probably thinks it's related to her question :) – ToneCrate Mar 04 '19 at 03:20
  • 1
    I'm not sure that's where their confusion was, but that's [object destructuring](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Object_destructuring) – Scott Rudiger Mar 04 '19 at 03:23
  • 1
    You're probably right now that I think about it, but who knows, might've added to the confusion – ToneCrate Mar 04 '19 at 03:32
  • 1
    Adding to that, does the variable within `{ } ` is a shorthand for represnting the values that are dynamically generated by the javascript? – Proteeti Prova Mar 04 '19 at 07:38
  • 1
    If you mean `const { count } = this.state;` that's the same as `const count = this.state.count;` just a different syntax (see the link in comment above). – Scott Rudiger Mar 04 '19 at 07:45