0

I understand that inheritance in JavaScript can be accomplished with the following (copied from MDN):

// 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.'

What I'm not understanding is why replacing:

Rectangle.prototype = Object.create(Shape.prototype);
Rectangle.prototype.constructor = Rectangle;

with:

Rectangle.prototype.prototype = Shape.prototype;

doesn't accomplish the same thing?

Performing a similar manipulation on an instance seems to work fine. Example:

var rect = new Rectangle();
rect.__proto__.__proto__ = Shape.prototype;

But manipulating prototypes this way is discouraged

yas
  • 3,520
  • 4
  • 25
  • 38

1 Answers1

1

Because inst.__proto__ == Rectangle.prototype. If you wanted to manipulate the prototype (i.e. from what it inherits) of your .prototype object, you would have needed to use

Rectangle.prototype.__proto__ = Shape.prototype;
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • How are `Rectangle.prototype.__proto__` and `Rectangle.prototype.prototype` different? – yas Jan 30 '15 at 15:47
  • One is *the* prototype, the other just a normal property that is used in the creation of instances with `new` and constructors. See also http://stackoverflow.com/q/650764/1048572 – Bergi Jan 30 '15 at 15:50