Javascript”;类“;带有参数的扩展

Javascript "class" extension with parameters?

本文关键字:参数 扩展 Javascript      更新时间:2023-09-26

我想从现有类"扩展"一个新类,并包括它的方法和参数构造。

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    

所以,这是我所了解的,显然有人错了。有人能给我建议吗?

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

System.call(this, name, hp);

此外,要注意Weapon.prototype = new System(name, hp);可能有副作用,最好使用

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

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

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}