gpt4 book ai didi

Javascript继承需要 parent parent 的功能?

转载 作者:行者123 更新时间:2023-11-28 06:54:08 27 4
gpt4 key购买 nike

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

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com