【问题标题】:About Javascript Prototype clarity [duplicate]关于 Javascript 原型清晰度 [重复]
【发布时间】:2016-05-13 20:39:54
【问题描述】:

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

// 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;

那么,我只想知道?

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

【问题讨论】:

标签: javascript prototype


【解决方案1】:
Rectangle.prototype.constructor = Rectangle;

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

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

function f(obj) {
  retur new obj.constructor;
}

用你的矩形。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-22
    • 1970-01-01
    • 1970-01-01
    • 2011-03-25
    • 1970-01-01
    • 2016-06-19
    • 1970-01-01
    相关资源
    最近更新 更多