Matt Hintzke Matt Hintzke - 1 year ago 99
Javascript Question

Prototype Inheritance Setup

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:


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);


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);


This example works as expected. The Square object inherits from the Rectangle, therefore, it has the ability to use the
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());

This logs the
new Rectangle()
which includes the
properties, then logs the
which logs the same thing except for the

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!


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
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?

Answer Source

I think you answered your question yourself. The difference between new Rectangle() and Object.create(Rectangle.prototype) is that the former calls the constructor and the latter doesn't. Because of that, you should always use Object.create(). Otherwise the constructor will be called twice (as you can see in your example).

Also, in ECMAScript 6 you can use the class syntax, which simplifies many things, like inheritance.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download