【发布时间】:2014-03-29 05:10:43
【问题描述】:
我目前正在编写一个 javascript 游戏,我正在尝试利用对象结构的继承,以及所有对象都继承自的基本 GameObject。但是,我不断遇到奇怪的行为。
虽然 GameObject 工作正常,但当它被子类调用时,它告诉我它的一些成员或我通过构造函数传递的对象成员没有定义,即使它们是。注意,我也在使用 pixi.js 引擎。具体来说,我正在将一个精灵传递给超类 GameObject,它告诉我该精灵的位置成员没有定义。
这打破了继承,子类不再是超类的实例。这两个类如下所示。我不认为这是 pixi 引擎的错误,而是我的一些语法错误。不幸的是,我对可能出现的问题感到困惑。另请注意,每个类都在一个单独的 js 文件中。
我想知道它为什么会这样,以及如何解决它。
游戏对象:
function GameObject(x_, y_, width_, height_, actor, stage) {
this.actor = actor;
var position = { x : x_, y : y_ }; //because I want the position data to be private
var size = { width : width_, height : height_ };
this.actor.position.x = position.x; //this is where it throws the reference error
this.actor.position.y = position.y;
this.actor.width = size.width;
this.actor.height = size.height;
stage.addChild(this.actor);
this.GetPosition = function() {
return position;
}
this.SetPosition = function(x, y) {
position.x = x;
position.y = y;
this.actor.position.x = position.x;
this.actor.position.y = position.y;
}
this.GetSize = function() {
return size;
}
this.SetSize = function(x, y) {
size.x = x;
size.y = y;
actor.width = size.x;
actor.height = size.y;
}
var collisionGroup = -1;
this.SetCollisionGroup = function(index) {
collisionGroup = index;
}
this.GetCollisionGroup = function() {
return collisionGroup;
}
}
继承自 GameObject 的子类:
FlappyBird.prototype = new GameObject();
FlappyBird.prototype.constructor = FlappyBird;
function FlappyBird(stage) {
GameObject.call(this, 50, 50, 50, 50, PIXI.Sprite.fromFrame("flappy01.png"), stage); //inherits from the game object
console.log(this instanceof GameObject);
console.log(this instanceof FlappyBird);
}
【问题讨论】:
标签: javascript inheritance identifier referenceerror pixi.js