我不明白 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)
我不明白这两行可能会发生什么变化,以便在它们存在时继承被破坏,并且我不确定以第二种方式进行继承是好的。有人可以告诉我这个吗? :)
如果你这样做
Spaceship.prototype = GameObject.prototype;
那么它们都引用同一个对象,所以你不妨将所有内容都放在GameObject
,如果你添加一些东西Spaceship.prototype
,它将被添加到GameObject.prototype
以及。您可以通过添加一些内容来轻松测试它Spaceship.prototype
任务完成后。例如,在您的情况下,您可以看到GameObject.prototype.constructor实际上是Spaceship http://jsfiddle.net/8w6gv/.
As for
Spaceship.prototype = new GameObject();
这会调用可能会产生不良副作用的构造函数,您宁愿使用:
Spaceship.prototype = Object.create(GameObject.prototype);
在哪里使用的Object.create
这里的功能归结为:
Object.create = function( proto ) {
function f(){}
f.prototype = proto;
return new f;
};
现代浏览器已经具备该功能。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)