3

I read here we can use Object.create to achieve inheritance

Here is an example with a Rectangle which inherits from Shape

function Shape() {}

function Rectangle() {
  Shape.call(this);
}

Rectangle.prototype = Object.create(Shape.prototype);
Rectangle.prototype.constructor = Rectangle;

var rect = new Rectangle();

I am wondering if using Object.setPrototypeOf instead of Object.create is correct ?

function Shape() {}

function Rectangle() {
  Shape.call(this);
}

Object.setPrototypeOf(Rectangle.prototype, Shape.prototype);

var rect = new Rectangle();

If it's correct, then I am wondering why so many examples show inheritance with Object.create because you need to worry about the constructor property when using this method.

With Object.setPrototypeOf you don't need to redefine the consctrutor prop, I find it safer and simpler.

Olivier Boissé
  • 15,834
  • 6
  • 38
  • 56
  • Setting the `constructor` property is more like a nice-to-have. It is not required. – trincot Nov 10 '18 at 18:29
  • it's required if we using in one of our method -> https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor#Changing_the_constructor_of_a_function – Olivier Boissé Nov 10 '18 at 18:41
  • That is the nice-to-have I talk about, but if one wanted to, they could keep this information in another way. It is not that JavaScript native methods or operators will break or behave differently if you don't set the `constructor` property. It is only there to facilitate. It is not essential. – trincot Nov 10 '18 at 18:45

1 Answers1

1

Sometimes your code may rely on the constructor property, which allows you to access the constructor without knowing its function name explicitly. But besides that, there is no real need to set it.

For example, the instanceof operator does not depend on it.

If you don't need to bother about it in your own suggested solution, then you also would not need it in the Object.create solution.

The reason to prefer the Object.create method is that Object.setPrototypeOf may impact the efficiency of your code, as is warned about in the mdn documentation. This does not happen with the Object.create method.

trincot
  • 317,000
  • 35
  • 244
  • 286
  • 1
    with my solution (using `Object.setPrototypeOf(Rectangle.prototype, Shape.prototype);`) it doesn't reaffect the `Rectangle.prototype` object, so `Cat.prototype.constructor === Cat` returns true (Cat.prototype.constructor is still valid) – Olivier Boissé Nov 10 '18 at 18:44
  • Yes, I see, but still: changing the `prototype` property is a relatively light operation compared to calling `setPrototypeOf`. – trincot Nov 10 '18 at 18:47
  • ok so it's preferable to use `Object.create` because of performance – Olivier Boissé Nov 10 '18 at 18:49
  • Yep, it boils down to that. – trincot Nov 10 '18 at 18:49