Home > Software design >  How do you extend a class with hardcoded properties and no constructor arguments in JavaScript?
How do you extend a class with hardcoded properties and no constructor arguments in JavaScript?

Time:10-26

I'm learning how classes work in JS and I'm trying to figure out how you can create a sub-class from a class with no constructor arguments and only hardcoded values

I just want the boss class to inherit the hardcoded properties of NPC, I'm changing the array in Boss but I want the logic for the weapon selection to stay the same.

class NPC {
  constructor() {
    this.weaponsArray = ['Sword', 'Gun', 'Axe']
    this.weapon = this.weaponsArray[Math.floor(Math.random * 3)]

  }
}

class Boss extends NPC {
  constructor() {
    super()
    this.weaponsArray = ['Mongo Hammer', 'Sword of Death', 'Gun of Pity']

  }
}


let bossguy = new Boss()

console.log(bossguy.weapon)

CodePudding user response:

I created a getter function to get weapon property, it will be set weapon if it is not set before:

class NPC {
  constructor() {
    this.weaponsArray = ['Sword', 'Gun', 'Axe'];
    //   this.weapon = this.weaponsArray[Math.floor(Math.random()* 3)]
  }
  getWeapon() {
    this.weapon = this.weapon || this.weaponsArray[Math.floor(Math.random() * 3)];
    return this.weapon;
  }
}

class Boss extends NPC {
  constructor() {
    super();
    this.weaponsArray = ['Mongo Hammer', 'Sword of Death', 'Gun of Pity'];
  }
}

let bossguy = new Boss();
console.log(bossguy.getWeapon());

CodePudding user response:

I think you could add an optional weapons argument to your constructor. You don't even have to extend the class to get a new type of NPC. I would also extract the generation of the weapons into its own function, so the logic is separate from the constructor. This way you can change the weapon by calling someNPC.selectWeapon(). The function would work even, if you extended the class

Example:

class NPC {
  constructor(weapons) {
    if (arguments.length == 0) {
      // No arguments were passed
      weapons = ['Sword', 'Gun', 'Axe']
    }

    this.weaponsArray = weapons
    this.weapon = this.selectWeapon()
  }
  selectWeapon() {
    return this.weaponsArray[Math.floor(Math.random() * this.weaponsArray.length)]
  }
}


let defaultNPC = new NPC()
let bossguy = new NPC(['Mongo Hammer', 'Sword of Death', 'Gun of Pity'])

console.log(bossguy.weapon)
console.log(defaultNPC.weapon)

If you insist on extending the class:

class Boss extends NPC {
  constructor() {
    super(['Mongo Hammer', 'Sword of Death', 'Gun of Pity'])
    this.weaponsArray = this.selectWeapon()
  }
}
  • Related