我不理解javascript中的这种行为来继承,我一直都这样定义它:
function GameObject(oImg, x, y) {
this.x = x;
this.y = y;
this.img = oImg;
this.hit = new Object();
this.hitBox.x = x;
this.hitBox.y = y;
this.hitBox.width = oImg.width;
this.hitBox.height = oImg.height;
}
Spaceship.prototype = new GameObject();
Spaceship.prototype.constructor = Spaceship;
function Spaceship(){
console.log("instantiate ship");
GameObject.apply(this, arguments);
this.vx = 0;
this.vy = 0;
this.speed = 3;
this.friction = 0.94;
}
但就我而言,这些行:
this.hitBox.width = oImg.width;
this.hitBox.height = oImg.height;
当我在Spaceship构造函数中执行console.log(this)时,可以看到 proto
属性设置为Spaceship而不是GameObject,如果删除它们,则将其设置为GameObject。
如果我使用:
Spaceship.prototype = GameObject.prototype;
我对此没有更多问题。之所以阻止我,是因为我有另一个具有add()方法的对象,并使用以下代码检查GameObject的对象是否插入:
if(object instanceof GameObject)
我不明白这两行可能会发生什么变化,因此当它们出现时继承会中断,我不确定第二种方式继承是好的。有人可以启发我吗?:)