[英]JavaScript inheritance, superclass identifier in subclass is not defined, even though it is
我目前正在編寫一個JavaScript游戲,並且試圖利用對對象結構的繼承以及所有對象都從其繼承的基本GameObject的優勢。 但是,我一直在面對奇怪的行為。
盡管GameObject可以正常工作,但是當它被子類調用時,它告訴我,即使通過構造函數,我通過構造函數傳遞的某些成員或對象成員也未定義。 注意,我也在使用pixi.js引擎。 具體而言,要進行的是將一個Sprite傳遞給超類GameObject,它告訴我該Sprite的position成員未定義。
這會中斷繼承,並且子類不再是超類的實例。 這兩個類如下所示。 我不認為這是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);
}
當您在此處調用GameObject
函數時:
FlappyBird.prototype = new GameObject();
...您沒有傳遞任何參數,因此很顯然,成員(如actor
)希望這些參數具有undefined
值。 因此this.actor.position
將失敗,並出現TypeError 。
更好的方法是這樣做:
FlappyBird.prototype = Object.create(GameObject.prototype);
...因為在FlappyBird.prototype
上不需要每個實例的東西。
問題中的代碼已更新。
這顯然將是一個問題,因為您將要進行無限遞歸。
function FlappyBird(stage) { // vv---Will infinitely recurse FlappyBird.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); }
您可能打算改為調用 GameObject
function FlappyBird(stage) { // vv---Applies the `GameObject` constructor to the `FlappyBird` object. 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); }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.