I've probably read 15 different books, articles, or SO questions related to JavaScript Prototypal Inheritance and each had slightly different ways of doing things, so I wanted to get this figured out once and for all:
Example
function Rectangle(h, w){
this.height = h;
this.width = w;
console.log("Rectangle ctor: "+ this.height + "x" + this.width);
}
Rectangle.prototype.getArea = function(){
return this.height * this.width;
}
var a = new Rectangle(3, 4);
console.log(a.getArea());
function Square(l){
this.height = l;
this.width = l;
console.log("Square ctor");
}
Square.prototype = new Rectangle();
Square.prototype.constructor = Square;
var b = new Square(5);
console.log(b.getArea());
This example works as expected. The Square object inherits from the Rectangle, therefore, it has the ability to use the getArea()
method. However, there is 1 thing I always see being done differently depending on where I look.
Instead of doing Square.prototype = new Rectangle()
, I have seen people use Square.prototype = Object.create(Rectangle.prototype)
. When I test this out, both appear to function in the same way, the only difference I notice is when I do this:
console.log(new Rectangle());
console.log(Object.create(Rectangle.prototype));
This logs the new Rectangle()
which includes the height
and width
properties, then logs the Object.create(Rectangle.prototype)
which logs the same thing except for the height
and width
.
So my question is, why do some people do it with one and not the other? Is one more beneficial than the other? The way I understand it, the one that uses new Rectangle()
will get the height and width properties on its prototype which could result in issues, correct?
Can someone please shed some light on this? Thanks!
EDIT
I also realized that when using new Rectangle()
as the prototype of Square, it actually calls the constructor (which may do something useful in some cases), whereas the Object.create()
method does not. Is the reasoning behind the 2 different usages related to the use case in terms of whether or not the constructor should be called to generate some object state that may be needed in the subtype?