1

It's been advised that Derived.prototype = Object.create(Base.prototype); is preferable to Derived.prototype = new Base(); (like in this SO answer).

That makes sense, but when I use this approach, like so:

function B(){};
B.prototype.doA = function(){};

function D(){};
D.prototype = Object.create(B.prototype);

var d = new D();

console.log(Object.getPrototypeOf(d)); 

it outputs Object {doA: function} to the console, and logging console.log(d) shows an object with __proto__: Object. Why is it not D {doA: function}?

Everything else seem to work:

d.doA();
d instanceOf D; // true
d instanceOf B; // true

fiddle

It seems weird. Am I doing something wrong?

Community
  • 1
  • 1
New Dev
  • 48,427
  • 12
  • 87
  • 129
  • 1
    Probably only weirdness of `console.log`. Try to set `D.protype.constructor = D;` and see whether the output changes. – Bergi Mar 02 '15 at 20:42
  • @Bergi, I think you are right. I was trying it in Chrome and it changed it to `D {constructor: function, doA: function}`. IE just shows [object Object] regardless. – New Dev Mar 02 '15 at 20:53

1 Answers1

1

jsFiddle Demo

When you use the Object.create approach, it is typically paired with a constructor assignment as well.

//...
D.prototype = Object.create(B.prototype);
D.prototype.constructor = D;
//...
Travis J
  • 81,153
  • 41
  • 202
  • 273
  • This kinda "works", but now adds `constructor` property to the output, which I guess is always there but hidden. So, is this an artifact of how console works? – New Dev Mar 02 '15 at 20:52
  • @NewDev - The constructor property should always be part of the output for instances of functions. When you use Object.create it only copies the prototype and that is why the constructor is simply object. For example, if you look at using `var d = new B();` in the fiddle, you will see that the log in the console includes the constructor property equal to function B – Travis J Mar 02 '15 at 20:55
  • It actually didn't for me in Chrome: http://jsfiddle.net/gfpq8c2a/1/. But seeing how IE doesn't show any kind identifier at all, it seems like it is just a console implementation issue. – New Dev Mar 02 '15 at 20:58
  • @NewDev - You are only logging the object in your fiddle, which is different than the other scenarios. That is why it does not show up. http://jsfiddle.net/gfpq8c2a/2/ – Travis J Mar 02 '15 at 21:04