试图为游戏添加一点逻辑

时间:2013-09-04 01:07:20

标签: javascript constructor

我有打游戏,想要增加更多的互动,某种能力。 这是一个很好的方法吗?构造函数和所有能力列表或者我错过了一些更简单的方法吗?

var abilityConstructor = function(name, desc, icon, target, param, rate, duration) {
    this.name = name;         // Name of ability
    this.desc = desc;         // Ability's description
    this.icon = icon;         // Ability's icon
    this.target = target;     // If for self usage - 0, if for enemy - 1
    this.param = param;       // Which parameter is influenced (health - 0, damage - 1, speed - 2, missing rate - 3)
    this.rate = rate;         // Factor for dealing (ability's strength) 
    this.duration = duration; // Spells' duration (current round - 1, two rounds - 2, three rounds - 3)
}

// List of available rates for abilities
var lowRate = 0.1;
var midRate = 0.25;
var highRate = 0.5;

var testAbility = new abilityConstructor('Health reduction', 'Reduces health of the opponent for 2 rounds', 'icon_path_here', 1, 0, midRate, 2);

1 个答案:

答案 0 :(得分:0)

嗯,首先按惯例,最好将构造函数大写,因为它有助于将它们标识为这样,并且你通常也不会附加构造函数字。

此外,它主要是一种偏好,但是当你开始有很多参数时,我更喜欢将一个dataoptions对象作为参数。

最后,如果您只是复制配置,可以通过循环配置键来完成。

function Ability(data) {
    for (var k in data) {
        this[k] = data;
    }
}

但是,您可能无法进行一般性的概括,因此您可以像手动一样手动复制值,而不是循环使用。

function Ability(data) {
    this.name = data.name;
    //...
}

以下是调用构造函数的方法:

var testAbility = new Ability({
    name: 'Health reduction',
    ...
});

编辑:

这种结构的优点是你不必记住参数顺序,当一些参数可能是选项时,它也简化了你的生活。您可以简单地省略数据对象中的键,而不是传递undefined。这种模式几乎用在每个JavaScript库中,包括jQuery。但是,由于每次都必须创建数据对象,因此您会牺牲性能。如果性能是一个真正的问题,我强烈建议您尝试这种模式并回避初始解决方案。