2012-11-10 136 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); 
相關問題