【发布时间】:2019-06-22 00:45:55
【问题描述】:
我是 Javascript 新手,我正在开发一个小游戏以更好地处理它。我正在尝试使用方法定义一个字符对象,但由于某种原因,我的 IDE 出现了奇怪的错误,“函数语句上的标签‘updateHealth’,函数声明中缺少名称”。我只是想弄清楚我做错了什么。在我的代码中,display 是角色的生命值在屏幕上的显示方式。
function Character(display) {
this.health = 100;
this.display = display;
// updates the health on the screen
updateHealth: function() {
if(health == 100) {
this.display.innerText = 'HP: ' + health;
}
else if(health > 10 && health < 100) {
this.display.innerText = 'HP: 0' + health;
}
else if(health < 10 && health > 0) {
this.display.innerText = 'HP: 00' + health;
}
else {
this.display.innerText = 'HP: 000';
}
}
// returns true if character has died
checkForDeath: function() {
if(health <= 0) return true;
else return false;
}
// function used when damage is inflicted on
// a character object
takeDamange: function(damage) {
this.health -= damage;
}
// handles the four possible moves
// opponent is null because if player heals
// then it does not make sense for there to be
// an opponent
makeMove: function(move, opponent=null) {
switch(move) {
case 'PUNCH':
opponent.takeDamage(parseInt(Math.random() * 100) % 10);
opponent.updateHealth();
break;
case 'HEAL':
this.health += 20;
break;
case 'KICK':
opponent.takeDamage(parseInt(Math.random() * 100) % 20);
opponent.updateHealth();
break;
case 'EXTERMINATE':
opponent.takeDamage(opponent.health);
opponent.updateHealth();
break;
}
return opponent.checkForDeath();
}
}
【问题讨论】:
-
为什么不使用
class语法? -
将
takeDamange重命名为takeDamage有帮助吗? -
@APerson 没有,但我错过了,谢谢
-
@jhpratt 什么是类语法?我刚刚通读了 MDN javascript 指南,它表明这是制作课程的唯一方法
-
你怎么打电话给
makeMove?我们在此代码示例中看不到它。
标签: javascript object methods