John Abraham
John Abraham

Reputation: 18791

Why do you reset an objects constructor when a subclass extends superclass?

Question: Why does the example set the Rectangle.prototype.constructor back to Rectangle when the subclass extends superclass? Is this a best practice? Is it to illustrate that it gets reset? Because the example works regardless.

            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(rect);
            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.

Upvotes: 1

Views: 181

Answers (1)

Mark Robson
Mark Robson

Reputation: 1328

when Rectangle.prototype = Object.create(Shape.prototype); is run, it will by default set the constructor of the Rectangle to be Shape.prototype.constructor - which is not what you want. Now you have to go ahead and explicitly set the Rectangle.prototype.constructor back to be the Rectangle constructor function, so any new objects will be Rectangle objects. Paste your code here: http://www.objectplayground.com/, select "classical inheritance", and change "rect" to " this.instance = new Rectangle();". Play around with it, comment out the line and see what difference it makes.

Hope that makes sense!

Upvotes: 2

Related Questions