0

我有格斗游戏,想增加一点互动,一些能力。这是一个好方法吗?构造函数和所有能力的列表,还是我错过了一些更简单的方法?

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);
4

1 回答 1

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。但是,由于每次都必须创建数据对象,因此您会稍微牺牲性能。如果性能是一个真正的问题,我强烈建议您尝试这种模式并回退到您的初始解决方案。

于 2013-09-04T01:23:54.940 回答