關於js中prototype的理解:javascript
1 ///Javascript繼承機制的設計思想引用http://www.ruanyifeng.com/blog/2011/06/designing_ideas_of_inheritance_mechanism_in_javascript.html 2 //一個對象都是一個構造函數的實例化 全部的須要共享的方法和屬性都放在了prototype中,成爲prototype的屬性或者方法 3 //而私有的方法和屬性則放在構造函數中 4 5 //關於prototype的測試實驗 6 function Animail(name){ 7 this.name = name ; 8 } 9 Animail.prototype.spcize = "1"; //spcize 須要共享的屬性或者方法 10 11 12 13 14 var a1 = new Animail("apple"); 15 var a2 = new Animail("banana"); 16 17 //這邊是用的prototype的屬性的引用 18 console.log(a1.spcize); 19 console.log(a2.spcize); 20 21 //應該是從新建立了spcize對象,覆蓋原來的引用,而後進行賦值(猜想) 22 a1.spcize = "2"; 23 a2.spcize = "3"; 24 25 console.log(a1.spcize); 26 console.log(a2.spcize); 27 28 delete a1.spcize;//刪除對象specize以後,a1.specize編程Animail。prototype。specize的引用 29 //delete a2.spcize; 30 31 Animail.prototype.spcize = "5"; 32 33 console.log(a1.spcize); 34 console.log(a2.spcize);
js中對prototype對象繼承的一個實例:html
1 //只得考慮的原型鏈的一段代碼 2 //實例化triangle,去調用Triangle的構造函數,注意此時prototype是爲空的,因此此時的實例化對象triangle中的prototype爲空,因此以後去調用getAre報錯 3 //緊接着會去調用Ploygon構造函數,而且對Polygon的prototype進行初始化 4 //而後對Triangle的prototype進行初始化,因此以後第二個實例化的對象就有getAre方法了。 5 6 7 //如何更改在全部triangle對象實例化以前,先將Triangle方法的prototype與Polygon的實例化對象綁定,這是實例化triangle對象會有一個getAre的引用(連接),而後在其調用 8 //調用實例化構造函數的時候會去重載prototype的getAre方法,由於是引用因此triangle對象的方法也被改變了。 9 function Polygon(iSide){ 10 console.log("Polygon constructor"); 11 this.side = iSide; 12 if(typeof Polygon._init == "undefined"){ 13 console.log("Polygon protype"); 14 Polygon.prototype.getArea = function(){ 15 return 0; 16 }; 17 }; 18 Polygon._init = true; 19 }; 20 21 function Triangle(iBase,iHeight){ 22 console.log("Triangle consturctor"); 23 Polygon.call(this,3); 24 this.base = iBase ; 25 this.height = iHeight; 26 27 if(typeof Triangle._init == "undefined"){ 28 Triangle.prototype = new Polygon(); //將這句話註釋掉 29 //console.log(Triangle.prototype.getArea()); 30 console.log("triangle prototype"); 31 32 Triangle.prototype.getArea = function(){ 33 return 0.5 * this.height * this.base; 34 }; 35 }; 36 Triangle._init = true; 37 }; 38 //Triangle.prototype = new Polygon(); //在這添加原型與實例化對象的綁定。 39 var triangle = new Triangle(3,4); 40 41 var triangle2 = new Triangle(3,4); 42 //console.log(triangle2.base); 43 //console.log(triangle2.height); 44 //console.log(triangle2.side); 45 console.log(triangle2.getArea()); 46 console.log(triangle.getArea());
本人連接至:java
http://blog.csdn.net/w329636271/article/details/21224403編程
http://blog.csdn.net/w329636271/article/details/21171857app
若有侵權請告知,本人當即刪ide