【发布时间】:2018-04-30 04:27:02
【问题描述】:
我从 Object.create() 上的 MDN 文章中获取了以下代码来理解相同的内容。
// Shape - superclass
function Shape() {
this.x = 0;
this.y = 0;
}
function Rectangle() {
Shape.call(this);
}
Rectangle.prototype = Object.create(Shape.prototype);
Rectangle.prototype.constructor = Rectangle;
var rect = new Rectangle();
console.log(rect.y);
我注释掉了以下两行,但仍然按预期工作。那么这段代码中Object.create()方法的意义是什么?为什么示例中已经演示了这种方法?
Rectangle.prototype = Object.create(Shape.prototype);
Rectangle.prototype.constructor = Rectangle;
【问题讨论】:
-
您省略了示例中一些非常关键的部分——定义
Shape原型的部分,以及显示rect调用这些函数的能力的部分。 developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… -
@CertainPerformance :
Rectangle.prototype.constructor = Rectangle行真的需要吗?
标签: javascript