Home > Net >  How can i put an object inside a list on Initialization
How can i put an object inside a list on Initialization

Time:12-26

So i have a Card class:

class Card {
    constructor(name = "", portrait = "", bloodCost = 0, boneCost = 0, power = 0, health = 1, sigilList = ["No sigil"]) {
        this.name = name
        this.portrait = portrait;
        this.bloodCost = bloodCost;
        this.boneCost = boneCost;
        this.power = power;
        this.health = health;
        this.sigilList = sigilList;
    }
}

And a list call cardPool. So how can I put a new Card object inside the cardPool list on initialize. For example:

console.log(cardPool)
// []

newCard = new Card("Test", "hi")
console.log(cardPool)
//
[
  Card {
    name: 'Test',
    portrait: 'hi',
    bloodCost: 0,
    boneCost: 0,
    power: 0,
    health: 1,
    sigilList: [ 'No sigil' ]
  }
]

CodePudding user response:

The solution I end up using is the one post by @TheBombSquad. By just writing cardPool.push(this) in the constructor

CodePudding user response:

Use Proxy with the construct trap.

const cardPool = [];

class _Card {
  constructor(name = "", portrait = "", bloodCost = 0, boneCost = 0, power = 0, health = 1, sigilList = ["No sigil"]) {
    this.name = name
    this.portrait = portrait;
    this.bloodCost = bloodCost;
    this.boneCost = boneCost;
    this.power = power;
    this.health = health;
    this.sigilList = sigilList;
  }
}

const Card = new Proxy(_Card, {
  construct(target, args){
    // Create an actual Card instance.
    const newCard = new target(...args);

    // Push the instance into cardPool.
    cardPool.push(newCard);

    // Return the created instance to be used like normal.
    return newCard;
  }
});

new Card('One', '1');
new Card('Two', '2');
new Card('Three', '3');

console.log(cardPool);

Creating a proxy is like appointing a middleman between you and the target object. A trap is like an instruction to the middleman of what it should do and when.

So when you use a Proxy with "construct" trap, it's basically telling the middleman to do something when new <target> is called. And in this case, the "something" is the cardPool push.

By doing this, you can always reuse the original _Card class for anything else where you don't want it to be pushed into cardPool.

  • Related