這是我的小程序。當我在調試模式下檢查rec的值時,對象是Base {x = 0,y = 0,w = 10,更多...}。它應該是矩形嗎?另外constructor.prototype是Base。爲什麼不塑造?爲什麼對象和constructor.prototype在JavaScript中設置爲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;
}
可能是因爲'Rectangle.prototype.constructor'是'Base'。 –
_Also的constructor.prototype是Base._你必須像'Rectangle.prototype.constructor = Rectangle'重定向構造函數' – elclanrs
注意,對於本地對象,'typeof object =='xml''永遠不會是true。 – RobG