下面是我的代码。我希望Player1,2将成为原型RPSPlayer的对象,并且每个对象都应具有单独的“历史”数组。但是现在,无论如何,每次我运行Player1.play()和Player2.play()时,它们都更新相同的“历史”数组并共享它。谢谢!
function RPSPlayer() {}
RPSPlayer.prototype.numOfWins = 0;
RPSPlayer.prototype.history = [];
RPSPlayer.prototype.myCurrPick;
RPSPlayer.prototype.getW = function () {return this.numOfWins;};
RPSPlayer.prototype.choose = function (item) {
this.history.push(item);
};
Player1 = new RPSPlayer();
Player1.play = function(){
var randomnumber=Math.floor(Math.random()*3);
if(randomnumber==0){this.currPick = "rock";}
else if(randomnumber==1){this.currPick = "paper";}
else{this.currPick = "scissors";}
this.choose(this.currPick);
return this.currPick;
};
Player2 = new RPSPlayer();
Player2.play = function(){
this.choose("rock");
this.currPick = "rock";
return "rock";
};
最佳答案
您必须在构造函数中初始化实例属性:
function RPSPlayer() {
this.history = [];
}
分配给
RPSPlayer.prototype
属性的每个值在所有实例之间共享(这是原型的目的之一)。关于javascript - 使用Java脚本面向对象,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8190982/