简体   繁体   中英

Javascript OOP Constructor with array or sub-object?

I am new to true OOP but I understand javascript pretty alright. I'm trying to make new objects using a constructor pattern but I would like to make one of the properties an array.

Here's an example of what I'm trying to do:

function Walker(name, type, ws, bs, s, armor, i, a, hp) {
    this.name = name;
    this.type = type;
    this.ws = ws;
    this.bs = bs;
    this.s = s;
    this.armor = new Array("f", "s", "r");
    this.i = i;
    this.a = a;
    this.hp = hp;
}

This is for a game some of you might know (and only for personal use, as the company who created the game has a stick up their... for their IP)

As you can see, the armor property is going to have 3 properties inside of it. The reason I'm doing it this way is because there is already a property named s , so I don't want that property and the armor property of s to be mixed up.

I am making a new walker and trying to log the armor like below:

var specificWalker = new Walker("Specific Walker", "Vehicle", 5, 5, 6, [12, 12, 10], 4, 2, 3);

console.log(specificWalker.armor[0]);

Though, of course this isn't working because armor[0] is always equal to "f" and I don't know how to override that that part of the array.

Ideally, what I would like to do is be able to log the armor this way:

console.log(specificWalker.armor.f) //Should log "12"

But I'm unsure on how to make an object inside of an object.

Can anyone help on this one?

You just need to create an Object, instead of an Array, like this

this.armor = ["f", "s", "r"].reduce(function(result, current, index) {
    result[current] = armor[index];
    return result;
}, {});

Now, this.armor is not an Array, but an Object. When you print specificWalker.armor , you will get something like this

{ f: 12, s: 12, r: 10 }

and then you can access f , like you wanted

console.log(specificWalker.armor.f);
// 12

i think you have so many arguments on the constructor, i'd do it this way:

function Walker(prop) {
    this.name = prop.name;
    this.type = prop.type;
    this.ws = prop.ws;
    this.bs = prop.bs;
    this.s = prop.s;
    this.armor = prop.armor;
    this.i = prop.i;
    this.a = prop.a;
    this.hp = prop.hp;
}

and call it this way

var walker = new Walker({
    name : "",
    type : "",
    ws : "",
    bs : "",
    s : "",
    armor : [12,12,39],
    i : "",
    a : "",
    hp : ""
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM