簡體   English   中英

JavaScript-為什么設置原型原型無效?

[英]JavaScript - why doesn't setting prototypes prototype work?

我了解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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM