简体   繁体   English

关于在MDN上标题为“Object.create()”的文档中的javascript继承的困惑

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM