我一直在阅读关于Object.create的MSD文档,偶然发现了这个例子。
// 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;
所以我想知道的就是?
这样做的原因是什么(在对象检查或其他方面保持理智)
发布于 2016-02-04 17:52:36
Rectangle.prototype.constructor =矩形;
属性constructor指的是对象的构造函数。但是当你用其他对象替换prototype时,你就失去了它。如果你想让这个属性正确(但在大多数情况下你不需要它),你必须显式地分配它。
所以,现在你可以做一些奇怪的事情,比如
function f(obj) {
retur new obj.constructor;
}用你的长方体。
https://stackoverflow.com/questions/35197566
复制相似问题