我是JavaScript的新手,我编写了调用虚拟用户的代码:
function User(){
this.name = ""
this.life = 100
this.givingLifeToAplayer = function(PlayerName){
PlayerName.life += 1
console.log(this.name + " gave 1 life to " + PlayerName.name)
}
}
var Yani = new User()
var jenny = new User()
var Robert = new User()
Yani.name = "Yani"
jenny.name = "Jenny"
Robert.name = "Robert";
Yani.givingLifeToAplayer(jenny)
console.log("Yani has " + Yani.life + " Jenny has " + jenny.life)
jenny.givingLifeToAplayer(Robert)
console.log("Jenny has " + jenny.life + " is the biggest score to " + Robert.life)
每当用户将life
传递给其他用户时,如何将life
增加1?
答案 0 :(得分:0)
你做得对。 PlayerName
是User.givingLifeToAplayer
中调用参数中对象的引用。编辑引用时,编辑两个对象(参数中的对象和PlayerName
)。编辑原始对象时也一样。
所以......你做到了。但是你的代码更具可读性:
function User(name) {
this.name = name;
this.life = 100;
this.addLifeTo = function(player) {
player.life ++; // increment operator
console.log(this.name + " gave 1 life to " + player.name);
}
}
var Yani = new User("Yani"),
Jenny = new User("Jenny"),
Robert = new User("Robert");
Yani.addLifeTo(Jenny);
console.log("Yani has " + Yani.life + ". Jenny has " + Jenny.life);
Jenny.addLifeTo(Robert);
console.log("Jenny has " + Jenny.life + "; it's the biggest score to " + Robert.life);
答案 1 :(得分:0)
Klaider Klai感谢您的回答
每当玩家将分数传给另一位玩家时,我想提高+1分,因为我可以看到Jenny
正在将1分传递给Robert
,但Robet的分数没有增加1分。
非常感谢