【问题标题】:Javascript "class" extension with parameters?带有参数的Javascript“类”扩展?
【发布时间】:2015-06-15 20:46:57
【问题描述】:

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

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    

所以,就我所知,有人显然是错的。 有人可以给我建议吗?

【问题讨论】:

  • call 需要参数Weapon = function(name, hp){ System.call(this, name, hp); }
  • 我可以询问哪种解决方案更好用吗?按照建议展开通话或使用 apply ?
  • @Cristian F this 可能会有所帮助

标签: javascript class object


【解决方案1】:

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

System.call(this, name, hp);

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

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

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

【讨论】:

    【解决方案2】:
    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}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-10
      • 1970-01-01
      相关资源
      最近更新 更多