2

I haven't been able to find a clear explanation of this. This is a straightforward example that I found on MDN. The only thing I don't understand is why the constructor is set. Can someone explain why this is needed? Is it for inheritance and so that the correct prototype chain is reffered to?

// 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.'
seasick
  • 1,094
  • 2
  • 15
  • 29
  • 2
    see this [Why is it necessary to set the prototype constructor?](http://stackoverflow.com/questions/8453887/why-is-it-necessary-to-set-the-prototype-constructor) – TwilightSun Oct 06 '15 at 05:03
  • 1
    @TwilightSun: note that you can flag the question as a duplicate, which will generate an auto-comment for you as well as letting users know who have the privilege of marking questions as duplicate. – Qantas 94 Heavy Oct 06 '15 at 05:36

1 Answers1

0

Whenever you create a function, say function foo(){}, the JS engine also creates an anonymous object and connects the two in a similar fashion.

foo.prototype = {};
foo.prototype.constructor = foo;

enter image description here

The property names "constructor" and "prototype" are so only because of semantics. It is possible that the standard names were:

foo.ping = {};
foo.ping.pong = foo;

And "the purpose of setting prototype.constructor" is simple - to be able to use the constructor function of that class.

If you don't need to call the constructor function, you can omit the property entirely.

To know more about the topic I recommend reading http://www.javascripttutorial.net/javascript-prototype/ and http://www.javascripttutorial.net/javascript-prototypal-inheritance/

zhirzh
  • 3,273
  • 3
  • 25
  • 30