2

I would like to "extend" a new class from an existing class and include it's methods and parameter construction.

System = function(name, hp){
  this.name = name;
  this.hp = [];
  this.setHP = function(hp){
     this.hp[0] = hp;
     this.hp[1] = hp;
  }
  this.setHP(hp);
}

Weapon = function(name, hp){
   System.call(this);
}

Weapon.prototype = new System(name, hp);
Weapon.prototype.constructor = Weapon;


var gun = new Weapon("Gun", 10);    // undefined name, hp
var hangar = new System("Hangar", 10);    // works    

So, this is as far as i got, and someone is obviously wrong. Can someone advise me ?

Christian F
  • 239
  • 2
  • 10

2 Answers2

1

You need to pass the arguments in the call:

System.call(this, name, hp);

Also, be aware that Weapon.prototype = new System(name, hp); can have side-effects, it is better practice to use:

Weapon.prototype = Object.create(System.prototype);

You can find polyfills for Object.create if you need to support ancient browsers.

elclanrs
  • 85,039
  • 19
  • 126
  • 159
1
System = function(name, hp){
  this.name = name;
  this.hp = [];
  this.setHP = function(hp){
     this.hp[0] = hp;
     this.hp[1] = hp;
  }
  this.setHP(hp);
}
Weapon = function(name, hp){
    System.apply(this, arguments);
}

console.log(new Weapon("Gun", 10));
console.log(new System("Hangar", 10));

Result:

Weapon {name: "Gun", hp: Array[2], setHP: function}
System {name: "Hangar", hp: Array[2], setHP: function}
cn007b
  • 14,506
  • 6
  • 48
  • 62