首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >关于Javascript Prototype clarity

关于Javascript Prototype clarity
EN

Stack Overflow用户
提问于 2016-02-04 17:47:31
回答 1查看 45关注 0票数 2

我一直在阅读关于Object.createMSD文档,偶然发现了这个例子。

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

// superclass method
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.
}

// subclass extends superclass
Rectangle.prototype = Object.create(Shape.prototype);
Rectangle.prototype.constructor = Rectangle;

var rect = new Rectangle();

console.log('Is rect an instance of Rectangle?', rect instanceof Rectangle);// true
console.log('Is rect an instance of Shape?', rect instanceof Shape);// true
rect.move(1, 1); // Outputs, 'Shape moved.'

尽管如此,除了其中的一部分,我理解了大部分代码。

Rectangle.prototype.constructor = Rectangle;

所以我想知道的就是?

这样做的原因是什么(在对象检查或其他方面保持理智)

EN

回答 1

Stack Overflow用户

发布于 2016-02-04 17:52:36

Rectangle.prototype.constructor =矩形;

属性constructor指的是对象的构造函数。但是当你用其他对象替换prototype时,你就失去了它。如果你想让这个属性正确(但在大多数情况下你不需要它),你必须显式地分配它。

所以,现在你可以做一些奇怪的事情,比如

代码语言:javascript
复制
function f(obj) {
  retur new obj.constructor;
}

用你的长方体。

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

https://stackoverflow.com/questions/35197566

复制
相关文章

相似问题

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