js中類定義函數時用prototype與不用的區別


轉載自:https://blog.csdn.net/yexudengzhidao/article/details/72866047

先看例子

function ListCommon2(first,second,third) 
{ 
    this.First=function () 
    { 
        alert("first do"+first); 
    } 
} 
//不加prototype的情況
ListCommon2.do1=function(first) 
{ 
    // this.First(); 
    alert("first do"+first); 
} 
//添加prototype的情況
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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM