Javascript继承需要 parent parent 的功能?

标签 javascript inheritance prototype

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

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/

关于Javascript继承需要 parent parent 的功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32706143/

相关文章:

javascript - 带参数的 Object.create

forms - 如何在 symfony2 表单集合中自定义数据原型(prototype)?

javascript - 如何使用 React js 中的上下文将函数从 FUNCTIONAL 传递到 CLASS 组件并在渲染之外访问它(不带 prop )?

javascript - 导出 react 样式 js 文件中定义的全局变量

javascript - Jquery 在滚动时触发动画一次

inheritance - 是否可以在 Scheme 中对函数/lambda/宏进行 "extend"处理?

javascript - 扩展 Array.prototype 返回未定义

javascript - 为什么当我打开浏览器时我的 jQuery 无法工作/显示?

c++ - 在不更改基类的情况下将一个派生类转换为另一个派生类

node.js - util.inherits - 如何在实例上调用 super 的方法?