Why wouldn’t I use Child.prototype = Parent.Prototype rather than Child.prototype = new Parent(); for Javascript inheritance?

If you do

Spaceship.prototype = GameObject.prototype;

Then they both refer to the same object, so you might as well have everything in GameObject, if you add something to Spaceship.prototype, it will be added to GameObject.prototype as well. You can easily test it by adding something to Spaceship.prototype after the assignment. For example, in your case you can see that GameObject.prototype.constructor is actually Spaceship.

As for

Spaceship.prototype = new GameObject();

This invokes the constructor which might have undesired side effects, you rather want to use:

Spaceship.prototype = Object.create(GameObject.prototype);

Where the used Object.create functionality here comes down to:

Object.create = function( proto ) {
    function f(){}
    f.prototype = proto;
    return new f;
};

Modern browsers already have the function though.

Leave a Comment