javascript - "this"关键字与多个对象

标签 javascript reactjs this

我知道“this”关键字指的是当前/即时对象。在观看 React.js 教程时,我看到讲师将关键字与多个对象一起使用。代码如下所示:

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;
  }
}

在 formatCount() 内部,为什么我们指的是 this.state 而不是 state.count ?另外,为什么不用 formatCount() 而不是 this.formatCount()?老师一直说this指的是当前对象,但他每次都在写this.objectname.properties。这是为什么?不能只用objectname来区分object吗?

最佳答案

您的讲师正在使用 public field declarations在类里面。

如果它有助于您的理解,没有此功能的等效代码将是:

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;
  }
}

换句话说,state = {...}styles = {...}只是声明 this.state 的简写和 this.styles在构造方法中。

编辑:如果您想更好地理解 this关键词,这里是another question you can reference .

关于javascript - "this"关键字与多个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54975845/

相关文章:

javascript - 根据嵌套键值对对象数组进行排序的最快方法

javascript - react : Why <Input> puts the event object at the end of the argument of the event handler

javascript - bind 和 var self=this 的区别?

javascript - 如何避免用作快速路由回调的函数中的 'this' 问题

javascript - 是否有用于 Javascript 的 sass 工具?

javascript - 在 keyup 上添加 2 个输入值以在第 3 个输入框中获得答案

javascript - 页面加载后仅获取新的 "child added"

android - 在不重新启动应用程序的情况下将 native 应用程序 LTR 更改为 RTL 更改

javascript - 不可变的 js Map() - 不理解 take() 和 skip()

jquery 将 $(this) 传递给其他函数