2

There are two piece of javascript code samples.
1-st code is:

var child1 = new Parent1();
child1.prototype = Object.create(Parent1);

2-nd code is:

var child2 = new Parent2();
child2.prototype = Object.create(Parent2.prototype);

So could you tell me please, what is the difference between them?

namco
  • 6,208
  • 20
  • 59
  • 83

1 Answers1

4

First of all - .prototype - is a property of constructor (e.g. function) not object. It means, all objects created with your constructor will have constructor prototype property as prototype :)

To set prototype of created object, you can use __proto__ property or Object.setPrototypeOf method, but be aware, that both are part of new ES2015 standard, which is not fully supported by all browsers.

Your code corrected will look like this

var child1 = new Parent1();
Object.setPrototypeOf(child1, Object.create(Parent1));
//vs
var child2 = new Parent2();
Object.setPrototypeOf(child2, Object.create(Parent2.prototype));

Difference is in 1st case you're setting Function object as prototype, which is kind of meaningless because it will contain only default function object porperties. In second one you're setting constructor's prototype as a prototype of constructed object, which is meaningless too, because it's already set after constructing.

Main part: code you've posted is not really correct and not commonly used. Prototypal inheritance should be used different. To know how, you can read answers from here

Interesting part: your code is still valid javascript, but it will do not work as you expected, because it's not working with prototypal inheritance.

Community
  • 1
  • 1
Andrey
  • 4,020
  • 21
  • 35