書中講動(dòng)態(tài)原型繼承實(shí)現(xiàn)繼承,給了一段錯(cuò)誤代碼function Polygon(sides){ this.sides = sides; if(typeof Polygon._initialized == "undefined"){ Polygon.prototype.getName = function(){ return "dash";
} alert(Polygon._initialized); Polygon._initialized = true;
}
}function Triangle(base, height){ Polygon.call(this,3); this.base = base; this.height = height; if(typeof Triangle._initialized == "undefined"){
**;** Triangle.prototype.getArea = function(){ return 0.5 * this.base * this.height;
}
Triangle._initialized = true;
}
}window.onload = function(){ var ri = new Triangle(10,20); var tri = new Triangle(20,40); alert(ri.getArea()); alert(ri.getName()); alert(ri.sides);
alert(tri.getArea());
alert(tri.getName()); alert(tri.sides);
}粗體部分的代碼有錯(cuò),書中原文解釋:從邏輯上講,這個(gè)位置是正確的,但從功能上講,卻是無效的.從技術(shù)上 說,在代碼運(yùn)行前,對(duì)象已經(jīng)被實(shí)例化,并與原始的prototype對(duì)象聯(lián)系在一起了.雖然用極晚綁定可使對(duì)原型對(duì)象的修改正確地反映出來,但替換 prototype對(duì)象不會(huì)對(duì)該對(duì)象產(chǎn)生任何影響.只有未來的對(duì)象(第二個(gè)以后的對(duì)象)實(shí)例才會(huì)反映出這種改變,這就使第一個(gè)實(shí)例變得不正確。
為什么技術(shù)上,對(duì)象被實(shí)例化?這段沒看懂
慕絲7291255
2023-04-24 18:14:26