首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Rectangle.prototype = Object.create( Shape.prototype )和Rectangle.prototype =Shape.prototype有什么区别?

Rectangle.prototype = Object.create( Shape.prototype )和Rectangle.prototype =Shape.prototype有什么区别?
EN

Stack Overflow用户
提问于 2016-07-26 12:38:04
回答 1查看 396关注 0票数 1

我读了下面的代码,开始想知道Rectangle.prototype = Object.create(Shape.prototype)Rectangle.prototype = Shape.prototype之间的区别是什么?因为Object.create( Shape.prototype )和Shape.prototype都返回一个对象。

代码语言:javascript
复制
//Shape - superclass
function Shape() {
  this.x = 0;
  this.y = 0;
}

Shape.prototype.move = function(x, y) {
    this.x += x;
    this.y += y;
    console.info("Shape moved.");
};

// Rectangle - subclass
function Rectangle() {
  Shape.call(this); //call super constructor.
}

Rectangle.prototype = Object.create(Shape.prototype);
EN

回答 1

Stack Overflow用户

发布于 2016-07-26 13:49:13

Rectangle.prototype = Shape.prototype;将矩形的原型指向与Shape的原型相同的对象,这意味着两个原型现在都是同一个对象。因此,如果您编辑Rectangle.prototype.method,它也会出现在Shape.prototype.method上。

Rectangle.prototype = Object.create(Shape.prototype);正在创建一个继承Shape的原型的新对象,并将其赋值给Rectangle的原型,这意味着如果您从这一点编辑Rectangle的原型,它不会影响Shape的原型。但是如果您编辑Shape的原型,您将通过继承在Rectangle中获得相同的属性。

有一个play - https://jsfiddle.net/j8o10zfn/

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38581106

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档