我读了下面的代码,开始想知道Rectangle.prototype = Object.create(Shape.prototype)和Rectangle.prototype = Shape.prototype之间的区别是什么?因为Object.create( Shape.prototype )和Shape.prototype都返回一个对象。
//Shape - superclass
function Shape() {
this.x = 0;
this.y = 0;
}
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.
}
Rectangle.prototype = Object.create(Shape.prototype);发布于 2016-07-26 13:49:13
Rectangle.prototype = Shape.prototype;将矩形的原型指向与Shape的原型相同的对象,这意味着两个原型现在都是同一个对象。因此,如果您编辑Rectangle.prototype.method,它也会出现在Shape.prototype.method上。
Rectangle.prototype = Object.create(Shape.prototype);正在创建一个继承Shape的原型的新对象,并将其赋值给Rectangle的原型,这意味着如果您从这一点编辑Rectangle的原型,它不会影响Shape的原型。但是如果您编辑Shape的原型,您将通过继承在Rectangle中获得相同的属性。
有一个play - https://jsfiddle.net/j8o10zfn/
https://stackoverflow.com/questions/38581106
复制相似问题