gpt4 book ai didi

javascript - 向类添加值

转载 作者:行者123 更新时间:2023-12-03 01:14:41 26 4
gpt4 key购买 nike

这里是 C# 开发人员。我想问一下如何向类添加值。

这是我的课:

class Players {
constructor(playerOne, playerTwo) {
this.playerOne = playerOne;
this.playerTwo = playerTwo;
}
}

这里我称之为它的构造函数:

handleClick() {
this.setState({ clicked: true });
Players(
document.getElementById("Select_Player1").value,
document.getElementById("Select_Player2").value
);
console.log(Players.playerOne);
console.log(Players.playerTwo);
}

我将其导出到文件末尾:

export { Players };

单击执行handleClick()的按钮后,应用程序返回错误:TypeError:无法将类作为函数调用

最佳答案

this.playerOnethis.playerTwo 不是静态的!

因此使用非静态:

class Players {
constructor(playerOne, playerTwo) {
this.playerOne = playerOne;
this.playerTwo = playerTwo;
}
}
var myP = new Players(
'test1',
'test2'
);
console.log(myP.playerOne);
console.log(myP.playerTwo);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react-dom.min.js"></script>

并使用静态:

class Players {
static setPlayers(playerOne, playerTwo) {
this.playerOne = playerOne;
this.playerTwo = playerTwo;
}
}
Players.setPlayers(
'test1',
'test2'
);
console.log(Players.playerOne);
console.log(Players.playerTwo);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react-dom.min.js"></script>

关于javascript - 向类添加值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52075070/

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