JavaScript - 为什么设置原型原型不起作用

JavaScript - why doesn't setting prototypes prototype work?

本文关键字:原型 不起作用 设置 为什么 JavaScript      更新时间:2023-09-26

我知道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;

但是不鼓励以这种方式操作原型

因为inst.__proto__ == Rectangle.prototype .如果你想操作你的.prototype对象的原型(即从它继承的内容),你需要使用

Rectangle.prototype.__proto__ = Shape.prototype;