I saw two different patterns and explanations. One from DailyJS and many others:
Rectangle.prototype = new Shape();
and then there’s Crockford’s here which implies just
Rectangle.prototype = Shape;
Now theory-wise, why you need to run the ‘new’? it runs the constructor function, yes. it also assigns the Rectangle’s prototype the Shape’s prototype. but we should be able to do inheritance just with a simple assignment of the parent into the prototype.
I wondered if the reason is prototype chaining. it seems, that in case 1, it will create a prototype chain. Meaning, that the Rectangle prototype will have the Shape prototype.
In the second case, the Rectangle’s prototype will just have Shape’s methods – but not Shape’s prototype methods.
Is that right? many thanks for any thoughts.
I can’t really see that.
Yet we actually don’t need (want) that, we only need the inheritance from
Shape.prototypeNot really.
new Shapecreates a new object which inherits fromShape.prototype, that’s what matters us. You’ve got that right.Yes, that’s correct. You should inherit from
Shape.prototype– but viaObject.create(Shape.prototype), not by creating an instance. See JavaScript inheritance: Object.create vs new or What is the reason [not] to use the ‘new’ keyword here?. This is what Crockford actually does – and even beforeObject.createwas introduced by EcmaScript 5.1, he found a clever way to do that with his helper functionwhich is now the common shim for
Object.createin browsers that don’t support it natively.