所以..这是我的问题..我有以下代码(示例):

var GameObject = function (posX, posY, width, height) {
 this.posX = posX;
 this.posY = posY;
 this.width = width;
 this.height = height;
 this.health = 100;
 this.doDamage = function (damage) {
   //Do nothing..
 }
}

var Creature = function (posX, posY, width, height) {
 this.constructor(posX, posY, width, height);
 this.doDamage = function (damage) {
  this.health -= damage;
 }
}
Creature.prototype = new GameObject();

var Enemy = function (posX, posY, width, height) {
 this.constructor(posX, posY, width, height);
}
Enemy.prototype = new Creature();

var e = new Enemy(40,40,10,10);
e.doDamage(20);


e.doDamage的输出是GameObject中定义的函数。但是我希望它是Creature中定义的函数。为什么不使用那个?

最佳答案

问题是,到调用Enemy构造函数时,您已经覆盖了两次this.constructor。因此,当您从Enemy类中调用this.constructor时,实际上是在调用GameObject构造函数并完全绕过Creature构造函数。要解决此问题,您需要显式调用构造函数。

因此,在您的Creature类中,您需要调用以下内容:

GameObject.call(this, posX, posY, width, height);


代替

this.constructor(posX, posY, width, height);


在您的Enemy类中,您需要改为调用以下命令:

Creature.call(this, posX, posY, width, height);




这是一个有效的现场演示:



var GameObject = function(posX, posY, width, height) {
  console.log("GameObject Constructor Called");
  this.posX = posX;
  this.posY = posY;
  this.width = width;
  this.height = height;
  this.health = 100;
  this.doDamage = function(damage) {
    //Do nothing..
  }
}

var Creature = function(posX, posY, width, height) {
  console.log("Creature Constructor Called");
  GameObject.call(this, posX, posY, width, height);
  this.doDamage = function(damage) {
    this.health -= damage;
  }
}
Creature.prototype = new GameObject();

var Enemy = function(posX, posY, width, height) {
  console.log("Enemy Constructor Called");
  Creature.call(this, posX, posY, width, height);
}
Enemy.prototype = new Creature();

console.log("Setup Done");

var e = new Enemy(40, 40, 10, 10);
e.doDamage(20);

document.getElementById("output").textContent = e.health;

<div>Initial Health: 100</div>
<div>20 health subtracted</div>
<div>Final Health: <span id="output" style="color: red;"></span></div>





JSFiddle版本:https://jsfiddle.net/5uq8rpe3/

10-07 18:09