[英]Confusion about inheritance in javascript on the document with heading “Object.create()” at MDN
I've been reading the this document at Mozilla Developer Network. 我一直在Mozilla开发者网络上阅读这篇文章。 In this document, a way for inheritance is defined as follows:
在本文档中,继承的方式定义如下:
// subclass extends superclass
Rectangle.prototype = Object.create(Shape.prototype);
Rectangle.prototype.constructor = Rectangle;
The question is, while assigning the Shape prototype to Rectangle prototype, why do I create a new Object as given in this code snippet? 问题是,在将Shape原型分配给Rectangle原型时,为什么要在此代码片段中创建一个新的Object? :
:
Rectangle.prototype = Object.create(Shape.prototype);
Why couldn't I assign the inheritance as this code snippet? 为什么我不能将继承分配为此代码段? :
:
Rectangle.prototype = Shape.prototype;
Because then anything you add to Rectangle.prototype
will also be in Shape.prototype
. 因为那么你添加到
Rectangle.prototype
任何东西也将在Shape.prototype
。
You'll also have the wrong constructor
property. 你也会有错误的
constructor
属性。
You want Rectangle.prototype
to inherit all members from Shape.prototype
, but still be an independent object that can have its own members. 您希望
Rectangle.prototype
继承Shape.prototype
所有成员,但仍然是可以拥有自己的成员的独立对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.