<分区>
此代码来自 MDN 上关于 Object.create()
的文章:
// 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();
倒数第三行是我感到困惑的一行。
有什么区别:
一个。现在怎么样了。
B. Rectangle.prototype = Object.create(Shape);
C. Rectangle.prototype = new Shape();
这 3 种方法最终不会产生相同的结果吗?在 rect
上定义相同的属性并使用相同的内存来定义它们?
是的,我已经阅读了解决 Object.create()
的其他 StackOverflow 问题。 不,他们没有完全解决我的困惑。