Christian F
Christian F

Reputation: 259

Javascript "class" extension with parameters?

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 ?

Upvotes: 2

Views: 75

Answers (2)

cn0047
cn0047

Reputation: 17071

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}

Upvotes: 1

elclanrs
elclanrs

Reputation: 94101

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.

Upvotes: 1

Related Questions