据我所知,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;
但是以这种方式操作原型(prototype)是 discouraged
最佳答案
因为inst.__proto__ == Rectangle.prototype
。如果您想操作 .prototype
对象的原型(prototype)(即它继承的内容),则需要使用
Rectangle.prototype.__proto__ = Shape.prototype;
关于JavaScript - 为什么设置原型(prototype)原型(prototype)不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28239422/