我一直在阅读 this Mozilla 开发者网络上的文档。在本文档中,定义了一种继承方式:
// subclass extends superclass
Rectangle.prototype = Object.create(Shape.prototype);
Rectangle.prototype.constructor = Rectangle;
问题是,在将 Shape 原型(prototype)分配给 Rectangle 原型(prototype)时,为什么我要创建一个新的对象,如此代码片段中给出的? :
Rectangle.prototype = Object.create(Shape.prototype);
为什么我不能将继承分配为此代码片段? :
Rectangle.prototype = Shape.prototype;
最佳答案
因为这样一来,您添加到 Rectangle.prototype
中的任何内容也会出现在 Shape.prototype
中。
您还会有错误的 constructor
属性。
您希望 Rectangle.prototype
继承 Shape.prototype
的所有成员,但仍然是一个可以拥有自己成员的独立对象。
关于javascript - MDN 标题为 "Object.create()"的文档中关于 javascript 继承的混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21000311/