3

I am implementing Prototypal inheritence in java script using simple assigning of prototype this is my code -

var Rectangle = function(heigth, width) {
  this.height = height;
  this.width  = width;  
}

Rectangle.prototype.area = function() {
  return this.height*this.width;
}

var Square = function(length) {
  this.height = this.width = length;
}

Square.prototype = Rectangle.prototype; 

var sqr1 = new Square(5);
console.log(sqr1.area());

But at the place of Square.prototype = Rectangle.prototype it is recommended to use Square.prototype = Object.create(Rectangle.prototype). Can anyone tell me the underlying difference because the above code is working fine.

1 Answer 1

1

Because the statement Square.prototype = Rectangle.prototype; actually copies the reference of the Rectangle.prototype and assigns it to Square.prototype. (Primitive types are copied by value and reference types are copied by reference).

So, if you are going to add some properties and methods on Square.prototype it'll modify the original Rectangle.prototype object and which is not what you want.

The Square.prototype = Object.create(Rectangle.prototype) creates a new object whose prototype is the Rectangle.prototype which is correct way.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.