Hate Names
Hate Names

Reputation: 1606

Giving an object multiple properties through 'new'?

Is there a way to give multiple properties in an easy fashion? For example I was trying to do this:

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
}

Now these are just two examples, but if I wanted to give many 'properties' to a single object, how would I go about doing it? The way I did it removes the previous new Spell properties and gives it only the Buff attributes. Is there a way to do it like I wrote above without having to write in extremely long arrays everything manually?

And before someone says the code is unreadable, which might be true, I have it entirely written in excel and it's all pretty and very easy to read, I just copy paste all the spells at once. I would prefer sticking with this method if possible.

Thank you very much for any help on the matter, thank you in advance.

EDIT:

Thanks for pointing me in the right direction Blender, I found a few helpful sources. Would the following solution be a good one or would you say there are better ways for me to do it?

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

Upvotes: 1

Views: 52

Answers (1)

OneOfOne
OneOfOne

Reputation: 99332

You will need complex objects one way or the other, here's my favorite way using OOP and inheritance.

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

Upvotes: 3

Related Questions