为什么我不使用Child.prototype = Parent.Prototype而不是Child.prototype = new Parent(); 对于Javascript继承?

Geo*_*Hug 8 javascript inheritance

我不明白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;
}
Run Code Online (Sandbox Code Playgroud)

但就我而言,这些线路:

    this.hitBox.width = oImg.width;
    this.hitBox.height = oImg.height;
Run Code Online (Sandbox Code Playgroud)

当我在我的Spaceship构造函数中执行console.log(this)时,我可以看到proto属性设置为Spaceship而不是GameObject,如果我删除它们,则将其设置为GameObject.

如果我使用:

 Spaceship.prototype = GameObject.prototype;
Run Code Online (Sandbox Code Playgroud)

我没有更多的问题.这阻止我的原因是我有另一个带有add()方法的对象,它使用以下代码检查GameObject的对象是否有效:

 if(object instanceof GameObject)
Run Code Online (Sandbox Code Playgroud)

我不明白这两行可能会改变什么,以便继承在它们存在时被破坏而我不确定继承第二种方式是好的.有人可以告诉我这件事吗?:)

Esa*_*ija 14

如果你这样做

Spaceship.prototype = GameObject.prototype;

然后他们都引用同一个对象,所以你可能还有所有东西GameObject,如果你添加了东西Spaceship.prototype,它也会被添加到其中GameObject.prototype.您可以通过Spaceship.prototype在分配后添加内容来轻松测试它.例如,在您的情况下,您可以看到GameObject.prototype.constructor实际上Spaceship.

至于

Spaceship.prototype = new GameObject();
Run Code Online (Sandbox Code Playgroud)

这将调用可能具有不良副作用的构造函数,您更愿意使用:

Spaceship.prototype = Object.create(GameObject.prototype);
Run Code Online (Sandbox Code Playgroud)

这里使用的Object.create功能归结为:

Object.create = function( proto ) {
    function f(){}
    f.prototype = proto;
    return new f;
};
Run Code Online (Sandbox Code Playgroud)

现代浏览器已经具备了这个功能.