我理解JavaScript中的继承可以通过以下方式完成(从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.'
我不理解的是替换原因:
Rectangle.prototype = Object.create(Shape.prototype);
Rectangle.prototype.constructor = Rectangle;
使用:
Rectangle.prototype.prototype = Shape.prototype;
没有完成同样的事情?
在实例上执行类似的操作似乎工作正常。例如:
var rect = new Rectangle();
rect.__proto__.__proto__ = Shape.prototype;
但是以这种方式操纵原型是discouraged
答案 0 :(得分:1)
因为inst.__proto__ == Rectangle.prototype
。如果你想操纵你的.prototype
对象的原型(即它继承的原型),你需要使用
Rectangle.prototype.__proto__ = Shape.prototype;