gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:10:56 25 4
gpt4 key购买 nike

这是来自 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com