1

Learning about inheritance in javascript I came across pseudoclassical inheritance. Here are 2 function constructors that I'm using:

function MySuperConstructor() {

}

MySuperConstructor.prototype = {
    constructor: MySuperConstructor,

    myMethod: function() {
       console.log("method called");
    }

}

function MyConstructor() {

}

What I'm confused is the difference between these 2 approaches:

MyConstructor.prototype = Object.create(MySuperConstructor.prototype);

and

MyConstructor.prototype = MySuperConstructor;

Is there any difference ?

Zed
  • 5,683
  • 11
  • 49
  • 81
  • 3
    The second one is simply outright wrong. – Bergi Jun 12 '14 at 12:51
  • Where did you see the second one? I agree with Bergi. Don't see a use case for that one. Even if you set Child.prototpye = Parent.prototpe for inheritance it would be wrong too. Given that Child could be Dog and Parent is Animal you'd set Dog to be the same as Animal (A Dog is an Animal) but an Animal is not a Dog. For example; you'd define Dog.prototype.bark and Fish inherits from Animal then Fish can bark. I'd stick with Object.create. For more info you can see this answer: http://stackoverflow.com/a/16063711/1641941 – HMR Jun 12 '14 at 13:17
  • sorry guys, I missed the new keyword before constructor in second statement...with new, those 2 statements would be equivalent ? – Zed Jun 12 '14 at 14:13

1 Answers1

3

There's a significant difference. In order to dispel the confusion when talking about the "prototype" property of a Function, and an object's prototype that is used for inheritance, I'll call object prototypes [[Prototype]].

Note that setting the property "prototype" of a Function - MyConstructor.prototype = SomeObject determines what an object's [[Prototype]] will be when created via new Function:

MyObj = new Constructor(); MyObj's [[Prototype]] is Constructor.prototype

Now for your code:

PrototypeObj = Object.create(MySuperConstructor.prototype);
MyConstructor.prototype = PrototypeObj;
MyObj = new MyConstructor();

Here's the [[Prototype]] chain for MyObj:

MyObj -> PrototypeObj -> MySuperConstructor.prototype(the object with myMethod) -> ...

If instead you use the second snippet:

MyConstructor.prototype = MySuperConstructor;
MyObj = new MyConstructor();

Here's the [[Prototype]] chain for MyObj:

MyObj -> MySuperConstructor -> MySuperConstructor's [[Prototype]] (which happens to be Function.prototype) -> ...

In the second case, the object you defined and set to MySuperConstructor.prototype is not in MyObj's prototype chain at all.

RobG
  • 142,382
  • 31
  • 172
  • 209
Sacho
  • 2,169
  • 1
  • 14
  • 13