我想在调用构造函数之前将对象的类作为prop传递,然后实例化它。
export class Knight implements AbstractCharacter {
public name = "Knight";
public hp = 500;
public damage = 1000;
}
反应成分:
export default class CharacterView extends React.Component {
constructor(props) {
super(props);
this.props.character = new props.character() // this isn't allowed
}
render() {
return(
<Text>
HP: {"" + this.props.character.hp}, Dmg: {this.props.character.damage}
</Text>
}
致电:
<CharacterView character = {Knight} /> // won't work
<CharacterView character = {new Knight()} /> // Would work, but it doesn't follow DRY principle. Also I would want to have multiple instances of Knight()
要在python中执行此操作,我将使用__new__
构造函数,而不是__init__
。 JS中是否有类似的东西,您可以在其中拦截构造函数?