【发布时间】:2014-08-03 05:52:28
【问题描述】:
所以,我想编写代码来创建具有随机统计数据的单位。
这是敌人构造函数:
function Enemy(name, atk, def, hp, mp, xp_val){
this.name = name;
this.atk = atk;
this.def= def;
this.hp = hp;
this.max_hp = hp;
this.mp = mp;
this.max_mp = mp;
this.xp_val = xp_val;
totalEnemies++;
}
这是创建随机敌人的补充代码。
function createEnemy(name, difficulty){
var atk = getIntBetween(5, 10);
var def = getIntBetween (0, 5);
var hp = getIntBetween(15, 25);
var mp = getIntBetween(0, 7);
var xp_val = getIntBetween(5, 10);
var multiplier;
if (difficulty === 1 || difficulty.toLowerCase() === "easy"){ multiplier = 1; }
if (difficulty === 2 || difficulty.toLowerCase() === "average"){ multiplier = 2; }
if (difficulty === 3 || difficulty.toLowerCase() === "challenge"){ multiplier = 4; }
if (difficulty === 4 || difficulty.toLowerCase() === "damn"){ multiplier = 7; }
if (difficulty === 5 || difficulty.toLowerCase() === "nightmare"){ multiplier = 11; }
atk *= multiplier;
def *=multiplier;
hp *= multiplier;
mp *= multiplier;
xp_val *= multiplier;
return new Enemy(name, atk, def, hp, mp, xp_val);
}
我尝试创建一个实例:
var goblin_02 = createEnemy("Goblin Dirtbag", 2);
我得到标题中的错误。这都是为了规避 JS 缺少重载的构造函数,我哪里做错了?
【问题讨论】:
-
你能告诉我们错误发生在哪一行吗?
-
也许 getIntBetween 函数没有定义?如果将函数的最后一行更改为此会发生什么?
return [name, atk, def, hp, mp, xp_val]; -
是的,你认为我应该添加它吗?如果我能告诉你,那就太好了,它可以“运行”得很好,但是一旦它到达这个部分/尝试使用它,我就会遇到问题。
标签: javascript oop object constructor