为什么必须使用关键字“this”而不是类名?

时间:2018-05-28 03:00:56

标签: 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;

2 个答案:

答案 0 :(得分:8)

因为在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;
    }
}

答案 1 :(得分:1)

因为

  

this关键字引用类的当前实例。它可以   用于从构造函数,实例方法中访问成员,   和实例访问器。

此规则之后是任何面向对象的编程语言。但是,如果强制类使用其名称获取实例,则它必须是静态的(不是类本身,而是属性和方法)。

为了您的目的,我们可以创建App类作为模块

class App {
  hello() { return 'Hello World'; }
}

export let AppInstance = new App ();

<强>用法

import { AppInstance } from './App';
AppInstance.hello();