javascript - 为什么必须使用关键字 "this"而不是类名?

标签 javascript reactjs this

这是来自 react.js 教程的代码,“this”关键字代表 App 类。所以我的问题是为什么我不能只写类名呢?

import React, { Component } from 'react';
import './App.css';
import Person from './Person/Person';

class App extends Component {

state = {
 persons: [
  { name: 'Max', age: 28 },
  { name: 'Manu', age: 29 },
  { name: 'Stephanie', age: 26 }
 ]
}

render() {
 return (
  <div className="App">
    <h1>Hi, I'm a React App</h1>
    <p>This is reallyyyyyyyy working!</p>
    <button> switch name</button>
    <Person name={App.state.persons[0].name} age={this.state.persons[0].age} />
    <Person name={this.state.persons[1].name} age={this.state.persons[1].age}>My Hobbies: Racing</Person>
    <Person name={this.state.persons[2].name} age={this.state.persons[2].age} />
  </div>
 );
// return React.createElement('div', {className: 'App'}, 
React.createElement('h1', null, 'Hi, I\'m a React App!!!'));
}
}

export default App;

最佳答案

因为在 JavaScript 中,当您指定类名时(特别是在类内部),您会获得对该类的引用,而不是对当前类实例的引用。实例属性和方法不能通过其类获得。同时 this 代表当前实例。

class App {
    test() {
        console.log(App); // "class App ..."
        console.log(this); // "[object Object]"
        console.log(App.foo()); // "1"
        console.log(this.foo()); // "2"
        console.log(this.constructor.foo()); // "1"; this.constructor is a reference to the current object class
    }

    static foo() {
        return 1;
    }

    foo() {
        return 2;
    }
}

关于javascript - 为什么必须使用关键字 "this"而不是类名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50558575/

相关文章:

javascript - Three.js 中的第一人称动画

reactjs - react : Show javascript inside render as plain text

javascript - 如何使用调用函数的元素的 "this"引用?

javascript - jquery "this"事件处理程序的绑定(bind)问题(相当于原型(prototype)中的 bindAsEventListener)

java - C++ this 在构造函数中?

javascript - KnockoutJS 数组

javascript - Expressjs中间件中定义的静态变量

javascript - CSS3 动画 - 无限悬停箭头

javascript - 尝试用字符串访问点表示法变量

node.js - 当存在嵌套的 package.json 文件时,Babel 不会编译文件