1

有没有办法以简单的方式提供多个属性?例如,我试图这样做:

object = new Spell( 50, 30, 5, 1, 30, 10 );
object = new Buff( "Armor", 50, 5 );

function Spell( baseDmg, dmgPerLvl, cd, cdPerLvl, cost, costPerLvl ) { 
this.baseDmg = baseDmg;
//...
//etc
// base damage, damage per level, cooldown, cooldown per level, cost, cost per level
}

function Buff( type, amount, duration );
this.type = type;
//etc
}

现在这只是两个例子,但如果我想为一个对象赋予许多“属性”,我该怎么做呢?我这样做的方式删除了以前的新 Spell 属性并只赋予它 Buff 属性。有没有办法像我上面写的那样做,而不必手动编写非常长的数组?

在有人说代码不可读之前,这可能是真的,我完全用 excel 编写了它,而且非常漂亮且易于阅读,我只需一次复制粘贴所有拼写。如果可能的话,我宁愿坚持这种方法。

非常感谢您对此事的任何帮助,在此先感谢您。

编辑:

感谢 Blender 为我指明了正确的方向,我找到了一些有用的资源。以下解决方案会是一个好的解决方案,还是您会说我有更好的方法来做到这一点?

object = new Spell( 50, 30, 5, 1, 30, 10 );
Spell.prototype.extendBuff = function( baseCC, ccPerLvl, ccText ) {
        this.baseCC = baseCC;
    this.ccPerLvl = ccPerLvl;
    this.ccText = ccText;
}
object.extendBuff( "Armor", 50, 5 );
4

1 回答 1

3

您将需要一种或另一种方式的复杂对象,这是我最喜欢使用 OOP 和继承的方式。

var Hero = function(name) {
    this.buffs = [];
    this.debuffs = [];
};
Hero.prototype = {
    cast: function(spell, target) {
        if(spell && spell.contructor === Buff) this.buffs.push(spell);
        // etc etc
    }
}

var Spell = function() { /* .... */};
var Buff = function() {
    Spell.apply(this, arguments);
}
Buff.prototype = Object.create(Spell.prototype, {
                constructor: {
                    value: Buff,
                    enumerable: false,
                    writable: true,
                    configurable: true
                }
            });
Buff.prototype.buffType = function() {}; //make sure this is after the Object.create line or it will get overriden

///////

var hero = new Hero('name');
hero.cast(new Spell('attack'), 'enemy');
hero.cast(new Buff('heal'), 'self');
于 2013-08-28T08:25:33.580 回答