js物件導向編程: js類定義函數時用不用prototype的區別?

來源:互聯網
上載者:User

一直在使用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();



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.