我的背景主要是Python和C#,但我正在帮助正在学习JavaScript入门的朋友学习编码。该课程于本周结束,但是它从未涵盖如何使用JavaScript编写类,因此我想我很快就整理了一个示例来说明它们的工作原理。唯一的问题是,每当我在类的一个实例上更改属性的值时,该属性在所有实例上都会更改。有办法使这项工作吗?
基本上,当我对troll1造成伤害时,troll2的生命值仍应为10(反之亦然)。相反,如果我对troll1造成三点伤害,则troll2和troll3的生命值也会变为7。
我尝试在构造函数外部设置健康状况,但是随后在调用类方法时却报错,即未定义健康状况(无论我使用this.health还是仅使用health)。
这是我制作的示例的html和js:
class trollEnemy {
constructor() {
this.health = 10;
}
takeDamage(damageAmount) {
this.health = this.health - damageAmount;
if (this.health > 0) {
document.getElementById("outputDiv").innerHTML = "Dealt " + damageAmount + " damage to the troll, the troll now has " + this.health + " health left";
} else {
document.getElementById("outputDiv").innerHTML = "Dealt " + damageAmount + " damage to the troll, the troll is now dead";
}
}
getHealth() {
if (this.health > 0)
document.getElementById("outputDiv").innerHTML = "The troll has " + this.health + " health left";
else
document.getElementById("outputDiv").innerHTML = "The troll is dead";
}
}
var troll1 = new trollEnemy();
var troll2 = new trollEnemy();
var troll3 = new trollEnemy();
function generateNewTroll(trollNumber) {
switch (trollNumber) {
case 1:
troll1 = new trollEnemy();
case 2:
troll2 = new trollEnemy();
case 3:
troll3 = new trollEnemy();
}
}
function damageTroll(trollNumber) {
switch (trollNumber) {
case 1:
troll1.takeDamage(document.getElementById("trollDamageAmount").value);
case 2:
troll2.takeDamage(document.getElementById("trollDamageAmount").value);
case 3:
troll3.takeDamage(document.getElementById("trollDamageAmount").value);
}
}
function checkTrollHealth(trollNumber) {
switch (trollNumber) {
case 1:
troll1.getHealth();
case 2:
troll2.getHealth();
case 3:
troll3.getHealth();
}
}
<button onclick="generateNewTroll(1)">Generate New Troll #1</button><button onclick="damageTroll(1)">Deal Damage To Troll #1</button> <button onclick="checkTrollHealth(1)">Check Troll #1 Health</button><br>
<button onclick="generateNewTroll(2)">Generate New Troll #2</button><button onclick="damageTroll(2)">Deal Damage To Troll #2</button> <button onclick="checkTrollHealth(2)">Check Troll #2 Health</button><br>
<button onclick="generateNewTroll(3)">Generate New Troll #3</button><button onclick="damageTroll(3)">Deal Damage To Troll #3</button> <button onclick="checkTrollHealth(3)">Check Troll #3 Health</button> Enter the amount of damage you want to deal to a
troll: <input type="text" id="trollDamageAmount">
<br>
<div id="outputDiv">Test</div>
答案 0 :(得分:3)
您需要将break
条语句放在switch条语句中,否则它们都将被调用:
switch(trollNumber)
{
case 1:
troll1.getHealth();
break
case 2:
troll2.getHealth();
break
case 3:
troll3.getHealth();
break
}
例如,事情不间断地通过:
let trollNumber = 1
switch(trollNumber)
{
case 1:
console.log(1)
case 2:
console.log(2)
case 3:
console.log(3)
}
如果将巨魔存储在数组中,您可能会更快乐。这将简化一切。例如,您可以编写如下函数:
function damageTroll(trollNumber){
trolls[trollNumber].getHealth()
}