function Polygon(sides){
if(this instanceof Polygon){
this.sides=sides;
this.getArea=function(){
return 0;
}
}else{
return new Polygon(sides);
}
}
function Rectangle(wifth,height){
Polygon.call(this,2);
this.width=this.width;
this.height=height;
this.getArea=function(){
return this.width * this.height;
};
}
var rect=new Rectangle(5,10);
alert(rect.sides); //undefined
這段程式碼是js高程三中P598-599的一個例子
我想問的是為什麼alert的是undefined呢?
開始
進入 Rectangle ,this 指向一個新 object,並且叫它 object1
執行到
以 object1 的名義進入 Polygon
object1 的原型是 Rectangle ,所以走到 else
再次進入 Polygon ,this 指向一個新對象,並且叫它為 object2
object2 的原型是 Polygon ,所以賜予 object2
sides
和getArea
回到 object1 的地盤,
Polygon.call(this,2);
回傳 object2 ,然後… 然後丟掉了。接著賜予 object1
undefined
的width
、height
和getArea
。最後,rect 得到了 object1
補上解,讓 Rectangle 共用 Polygon 的原型即可
在Rectangle中將Polygon的this指向了Rectangle的this,Rectangle作為構造函數使用時this指的是Rectangle的實例,即本例中的rect,而Polygon的原型並沒有在rect的原型鏈上,即this instanceof Polygon為false,所以走的是else內的return new Polygon(sides),沒有將sides掛到實例上,所以rect實例上也就不存在sides屬性。
還有Rectangle(wifth,height),width寫錯了
在你的例子中,Polygon 是個幹擾項,對 Rectangle 一點影響都沒有。
去掉
Polygon.call(this,2);
再看,能明白原因了麼印一下this,你就知道原因了
this.sides=sides 掛在了Polygon
return new Polygon(sides);//this 不再是呼叫的時候的Rectangle