2

I'm been reading through MSD doc about Object.create and I stumble upon this example.

// Shape - superclass
function Shape() {
  this.x = 0;
  this.y = 0;
}

// superclass method
Shape.prototype.move = function(x, y) {
  this.x += x;
  this.y += y;
  console.info('Shape moved.');
};

// Rectangle - subclass
function Rectangle() {
  Shape.call(this); // call super constructor.
}

// subclass extends superclass
Rectangle.prototype = Object.create(Shape.prototype);
Rectangle.prototype.constructor = Rectangle;

var rect = new Rectangle();

console.log('Is rect an instance of Rectangle?', rect instanceof Rectangle);// true
console.log('Is rect an instance of Shape?', rect instanceof Shape);// true
rect.move(1, 1); // Outputs, 'Shape moved.'

Although, I understand most part of the code except for one part.

Rectangle.prototype.constructor = Rectangle;

So, all I want to know is?

What is reason of doing so (to maintain sanity in term of object inspection or something else)

Ratatouille
  • 1,372
  • 5
  • 23
  • 50
  • Read here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor – jfriend00 Feb 04 '16 at 09:59

1 Answers1

0
Rectangle.prototype.constructor = Rectangle;

Property constructor refers to constructor of the object. But when you replace prototype by other object, you are losing it. If you want to have this property correct (but in most caces you don't need it), you have to assign it explicitly.

So, now you can do some weird things like

function f(obj) {
  retur new obj.constructor;
}

with your rectangles.

Qwertiy
  • 19,681
  • 15
  • 61
  • 128