“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....

问题:

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?


回答1:

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.

  • 发表于 2019-03-05 03:16
  • 阅读 ( 238 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除