这是我的小程序。当我在调试模式中检查rec的值时,对象是Base {x = 0,y = 0,w = 10,more ...}。它应该是矩形吗? constructor.prototype也是Base。为什么不塑造?
function Base() {
}
function Shape(x, y) {
this.x = x;
this.y = y;
}
Shape.prototype = new Base();
Shape.prototype.move = function(x, y) {
this.x += x;
this.y += y;
console.log("x = " + this.x + " y = " + this.y);
};
function Rectangle(x, y, w, h) {
Shape.call(this, x, y);
this.w = w;
this.h = h;
}
Rectangle.prototype = new Shape();
Rectangle.prototype.area = function() {
return this.w * this.h;
};
var rec = new Rectangle(0, 0, 10, 10);
console.log(instanceOf(rec, Rectangle));
function instanceOf(object, constructor) {
while (object != null) {
if (object == constructor.prototype)
return true;
if ( typeof object == 'xml') {
return constructor.prototype == XML.prototype;
}
object = object.__proto__;
}
return false;
}
答案 0 :(得分:0)
看看Why [not] to use the new
keyword here?。您可能不会使用它并创建它的新实例,而只是从Base.prototype
继承。
constructor.prototype也是Base。为什么不塑造?
我不确定你在这里指的是constructor
:
所有对象的constructor
属性为Base
,因为所有对象都从Base.prototype
对象继承此原型。设置继承链后,您没有覆盖它。这不是必要的,而是好的风格:Shape.prototype.constructor = Shape
和Rectangle.prototype.constructor = Rectangle
- 这些原型对象是从Base
继承的被覆盖的对象。
constructor
功能的instanceOf
参数。您传递Rectangle
,constructor.prototype
是Rectangle
的原型对象,从Base
继承但不同。
当我在调试模式中检查rec的值时,对象是Base {x = 0,y = 0,w = 10,more ...}
通常不是。 Base
是特别的,例如主持人对象?您的rec
对象是Base
的实例,因此可能会以不同的方式显示。
rec
只是一个继承自Rectangle.prototype
的{{1}}继承自Shape.prototype
的继承自Base.prototype
的对象。假设Base
是函数您定义的是Object.prototype
继承自null
。