JavaScript中的類添加通用方法

來源:互聯網
上載者:User

首先說明一點,JavaScript 不支援函數的重載,如果右多個函數名相同,它自己會調用距離他最近的那個,也就是最

後的那個函數,這個JS不支援函數重載的現象的東西需要特別的注意。

直接定義一個函數或者變數,他們是屬於全域函數或者全域變數,本質上他們是屬於window對象的。

然後還有對於JS中內建的對象,我們可以為他們提供一個通用的方法,這樣就不需要專門寫了。

代碼如下

[javascript]
//我們可以給類添加方法  
    var i = new Number(10); 
    Number.prototype.add=function(a){ 
        return this+a; 
    } 
     
    window.alert(i.add(20).add(30)); 
//我們可以給類添加方法
 var i = new Number(10);
 Number.prototype.add=function(a){
  return this+a;
 }
 
 window.alert(i.add(20).add(30));
這樣的話,我們就可以給Number這個對象的增加方法,我們就可以直接使用了。

再看一個代碼

[javascript]
Array.prototype.find=function(val){ 
    for(var i = 0; i < this.length; i++){ 
        if(this[i] == val){ 
        window.alert("下標為 "+i); 
        return; 
        } 
    } 
    window.alert("沒有"); 

 
var t = new Array(3); 
t[0] = 3; 
t[1] = 5; 
t[2] = 6; 
 
t.find(4); 
t.find(5); 
 Array.prototype.find=function(val){
  for(var i = 0; i < this.length; i++){
   if(this[i] == val){
   window.alert("下標為 "+i);
   return;
   }
  }
  window.alert("沒有");
 }
 
 var t = new Array(3);
 t[0] = 3;
 t[1] = 5;
 t[2] = 6;
 
 t.find(4);
 t.find(5);
這樣的話為Array對象提供了通用的方法,套用了this關鍵字,這樣的prototype可以為相當於類的東西提供方法,Mark一下

 

摘自  a352193394
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.