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.
constructorproperty is more like a nice-to-have. It is not required.constructorproperty. It is only there to facilitate. It is not essential.