3
在下面的代碼中,爲什麼instanceof對Shape和Rectangle都返回false?爲什麼rec的屬性包含超類的x和y?爲什麼instanceof在JavaScript中返回false?
function Shape(x, y) {
this.x=x;
this.y=y;
}
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 = Object.create(Shape.prototype);
Rectangle.prototype.area = function() {
return this.w * this.h;
};
var rec = new Rectangle(0,0,10,10);
console.log("instanceof = " + rec instanceof Shape);
console.log("instanceof = " + rec instanceof Rectangle);
rec.move(2,3);
console.log("area = " + rec.area());
console.log(Object.getOwnPropertyNames(rec));
你應該矩形設置的原型來新形狀()。如果您是JavaScript新手,則應該查看codeacademy.com。 –
@GlennFerrieLive:'Object.create(Shape.prototype)'是首選,因爲它不需要調用'Shape'構造函數,併爲您提供一個空對象。 –