cuốn sách gpt4 ai đã làm

Kế thừa Javascript yêu cầu chức năng của cha mẹ?

In lại Tác giả: Walker 123 更新时间:2023-11-28 06:54:08 27 4
mua khóa gpt4 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 中定义的函数。为什么不使用那个?

câu trả lời hay nhất

问题是,当您调用 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/

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

27 4 0
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress