带参数的Javascript“class”扩展名?

时间:2015-04-10 08:00:31

标签: javascript class object

我想"延伸"来自现有类的新类,包括它的方法和参数构造。

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    

所以,就我而言,有人显然是错的。 有人可以告诉我吗?

2 个答案:

答案 0 :(得分:1)

您需要在调用中传递参数:

System.call(this, name, hp);

另外,请注意Weapon.prototype = new System(name, hp);可能会产生副作用,最好使用以下方法:

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

如果您需要支持古老的浏览器,可以找到Object.create的填充。

答案 1 :(得分: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));

结果:

Weapon {name: "Gun", hp: Array[2], setHP: function}
System {name: "Hangar", hp: Array[2], setHP: function}