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.

3
  • Setting the constructor property is more like a nice-to-have. It is not required. Commented Nov 10, 2018 at 18:29
  • it's required if we using in one of our method -> developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Nov 10, 2018 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. Commented Nov 10, 2018 at 18:45

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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)
Yes, I see, but still: changing the prototype property is a relatively light operation compared to calling setPrototypeOf.
ok so it's preferable to use Object.create because of performance
Yep, it boils down to that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.