所以..这是我的问题..我有以下代码(示例):
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);
thay vì
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;
Initial Health: 100
20 health subtracted
Final Health:
JSFiddle 版本:https://jsfiddle.net/5uq8rpe3/
Tôi là một lập trình viên xuất sắc, rất giỏi!