【发布时间】:2015-04-25 22:04:54
【问题描述】:
我正在尝试为我的程序创建一种面向对象的方法。我读到这应该从 Sprite 创建一个 World 的继承,其中 Sprite 是父级,但是 Sprite.call(this, imagePath) 由于 imagePath 未定义而出现。我会假设调用中的其他变量也未定义。如何正确调用父变量?
function Sprite(spriteX, spriteY, spriteW, spriteH, scale, positionX, positionY, direction)
{
this.imagePath = world_sprite;
this.spriteX = spriteX;
this.spriteY = spriteY;
this.spriteW = spriteW;
this.spriteH = spriteH;
this.scale = scale;
this.positionX = positionX;
this.positionY = positionY;
this.direction = direction;
this.speed = 5;
this.noGravity = false;
this.direction = 0;
//Physics stuff
this.velX = 0;
this.velY = 0;
this.friction = 0.98;
};
function World(posX, posY, direction, xOffset, yOffset)
{
Sprite.call(this, imagePath, positionX, positionY, direction);
this.spriteX = 0;
this.spriteY = 0;
this.spriteW = 400;
this.spriteH = 400;
this.scale = 0.4;
this.xOffset = xOffset;
this.yOffset = yOffset;
this.lives = 3;
};
【问题讨论】:
-
在
World()函数中,您没有名为imagePath、positionX或positionY的变量或参数。所以当然这些是未定义的。 -
我认为 Sprite.call 会从 Sprite 获取这些变量?
-
不,
Sprite.call()正在调用进入Sprite()函数。在您进行调用时,不知道该函数内部发生了什么。你必须只使用你当时可用的东西。请参阅下面的答案,了解您可以做到这一点的一种方法。
标签: javascript oop object inheritance