2012-11-10 98 views
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)); 
+0

你应该矩形设置的原型来新形状()。如果您是JavaScript新手,则应该查看codeacademy.com。 –

+0

@GlennFerrieLive:'Object.create(Shape.prototype)'是首选,因为它不需要调用'Shape'构造函数,并为您提供一个空对象。 –

回答

9

由于+instanceof前评估。所以你问:

"instanceof = " + rec 

...一个String,是instanceof你的构造函数,这也不会是。

要么加括号强制顺序:

console.log("instanceof = " + (rec instanceof Shape)); 

或者,由于console.log接受任何数量的参数,把它作为自己的:

console.log("instanceof = ", rec instanceof Shape); 
相关问题