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'构造函数,并为您提供一个空对象。 –