一直在使用js編寫自以為是物件導向的方法,遇到一個問題,就是定義一個方法,如下:
function ListCommon2(first,second,third) { this.First=function () { alert("first do"+first); } } ListCommon2.do1=function(first) { // this.First(); alert("first do"+first); } ListCommon2.prototype.do2=function(first) { // this.First(); alert("first do"+first); }
兩種方法到底有什麼區別呢?用不用prototype有什麼作用呢?
測試代碼:
var t1=new ListCommon2("燒水1","泡茶1","喝1"); // t1.do1();//調用出錯 ListCommon2.do1("燒水1"); var t2=new ListCommon2("燒水2","泡茶2","喝2"); t2.do2("燒水2");// // ListCommon2.do2("燒水1");//調用出錯
經過測試發現,沒有使用prototype的方法相當於類的靜態方法,因此可以這樣調用,ListCommon2.do1("燒水1");,如果這樣調用就會出錯,t1.do1();
相反,使用prototype的方法相當於類的執行個體方法,只有new後才能使用,ListCommon2.do2("燒水1");這樣就會出錯
結論,使用 prototype定義的方法相當於類的執行個體方法,必須new後才能使用,函數中可以調用函數的限制也會類的執行個體方法的限制有些類似
使用 不使用prototype定義的方法相當於類的靜態方法,可以直接使用,不需要new,,函數中可以調用函數的限制也會類的靜態方法法的限制有些類似
例如不能調用this.First();
查看本欄目更多精彩內容:http://www.bianceng.cnhttp://www.bianceng.cn/webkf/script/