Mark Adel
Mark Adel

Reputation: 223

Why is Object.create() used in this case in prototypical inheritance?

Consider this code :-

function Rectangle(length, width) { 
    this.length = length;
    this.width = width;
}

Rectangle.prototype.getArea = function() {
    return this.length * this.width;
};

function Square(size) { 
    Rectangle.call(this, size, size);
}

Square.prototype = Object.create(Rectangle.prototype);

var rect = new Rectangle(5, 5);
var square = new Square(7);

console.log(rect.getArea());   // 25
console.log(square.getArea()); // 49

Why do we have to do the inheritance like this :-

Square.prototype = Object.create(Rectangle.prototype);

And not like this :-

Square.prototype = Rectangle.prototype;

They both seem to do the required task.

Upvotes: 2

Views: 58

Answers (2)

Pointy
Pointy

Reputation: 413720

Setting Square.prototype = Rectangle.prototype means that they're both the same object, which is almost certainly not what you want. A Square is a Rectangle, but a Rectangle is not a Square, so the behaviors will not be the same. You need two distinct prototype objects.

Using Object.create() is a clean way to create an object that has a given object (in this case, Rectangle.protoype) as the head of its prototype chain. The result is that Square.prototype is a distinct object, and can be given its own properties (special methods applicable to a square but not a rectangle), but it will also have access to methods from the Rectangle prototype.

So when you create a Square via new Square(100), you get an object whose direct prototype is the object created with Object.create() and (presumably) decorated with all sorts of interesting Square behaviors. That object, in turn, has Rectangle.prototype as the first thing in its prototype chain. The effect of that is that if you call, say, mysquare.area(), and area() is defined on the Rectangle prototype, the lookup will proceed from the Square instance, to the Square prototype, and then to the Rectangle prototype where the method will be found.

Upvotes: 4

AdamW
AdamW

Reputation: 184

Object.create adds another object on top of the target prototype. This means you can set properties on this object without modifying the original prototype

Upvotes: 2

Related Questions