【发布时间】:2015-03-20 16:41:50
【问题描述】:
这段代码来自Object.create()上的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();
倒数第三行是我感到困惑的那一行。
两者有什么区别:
A.现在怎么样了。
B.Rectangle.prototype = Object.create(Shape);
C.Rectangle.prototype = new Shape();
不是所有 3 个最终都会产生相同的结果吗?在rect 上定义的相同属性以及定义它们的相同内存使用?
是的,我已阅读解决 Object.create() 的其他 StackOverflow 问题。 不,他们没有完全解决我的困惑。
【问题讨论】:
标签: javascript inheritance prototype prototypal-inheritance