我一直在Mozilla开发者网络上阅读this文档。在本文档中,继承的方式定义如下:
// subclass extends superclass
Rectangle.prototype = Object.create(Shape.prototype);
Rectangle.prototype.constructor = Rectangle;
问题是,在将Shape原型分配给Rectangle原型时,为什么要在此代码片段中创建一个新的Object? :
Rectangle.prototype = Object.create(Shape.prototype);
为什么我不能将继承分配为此代码段? :
Rectangle.prototype = Shape.prototype;
答案 0 :(得分:3)
因为您添加到Rectangle.prototype
的任何内容也会出现在Shape.prototype
中
你也会有错误的constructor
财产。
您希望Rectangle.prototype
继承Shape.prototype
的所有成员,但仍然是一个可以拥有自己成员的独立对象。