gpt4 book ai didi

JavaScript - 子继承打破父

转载 作者:行者123 更新时间:2023-11-28 00:19:58 25 4
gpt4 key购买 nike

我对 JS 中的原型(prototype)继承还很陌生,我遇到了一个我无法弄清楚的奇怪错误。我们正在使用 canvas 编写游戏,我们的代码看起来像这样:

function GameObject() {
// Generic object that everything inherits from
this.x = 0;
this.y = 0;
this.dx = -0.5;
this.dy = 0;
this.width = 0;
this.height = 0;
this.sprite = new Image();
this.sprite.src = "";
}

function Block(x,y) {
this.x = x;
this.y = y;
this.width = 2 * TILE_SIZE;
this.height = 2 * TILE_SIZE;
this.sprite.src = "images/block/block3.png";
blocks.push(this); // Manager array
}

Block.prototype = new GameObject();
Block.prototype.constructor = Block;

这段代码工作正常。请注意,TILE_SIZE 是在一个单独的文件中定义的,该文件包含在 block 脚本之后 - 这在这里似乎不是问题。但是当我们添加如下代码时(在Block函数之后):

function Block_Turret(x,y) {}
Block_Turret.prototype = new Block();
Block_Turret.prototype.constructor = Block_Turret;

我收到一个 Uncaught ReferenceError,提示 TILE_SIZE 未在 Block 函数中定义!看起来 child 正在破坏 parent ,我不知道为什么会这样——这似乎是一个相当简单的继承场景。提前致谢!

最佳答案

第一部分代码有效是因为在第二部分代码之前您没有调用引用TILE_SIZE(即Block)的函数,其中变量被引用,并产生引用错误,因为正如您所解释的那样,它尚未定义。与继承无关,只是普通的旧 js。

细说一下,函数内部直到函数被调用时才执行,所以只要语法合法就不会报错,即使定义了函数,也就算你这么干,也一样用一个引用。

应该改变结构。独立的配置细节自然应该包含在相关代码之前(想想旧的 C 标准)。

关于JavaScript - 子继承打破父,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9659506/

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