JavaScript中的方法重載執行個體_javascript技巧

來源:互聯網
上載者:User

.NET裡面的方法重載用著的確很方便,哪Javascript裡面能不能也哪樣做呢?

Javasciprt裡面本生是沒有方法重載的功能,以前很多人的做法可能是直接少傳參數過去,然後在根據參數是否為 “undefined” 未定義來決定怎麼處理,從而實作類別似方法重載的功能。

例如:

複製代碼 代碼如下:

var showMessage = function(name,value,id){
    if(id != ”undefined”){
        alert(name+value+id);
    }
    else if(value != ”undefined”){
        alert(name + value);
    }
    else{
        alert(name);
    }
}

showMessage(”哈哈”);
showMessage(”哈哈”,”??”);
showMessage(”哈哈”,”??”,124124);

今天在Ajaxian上面看到了一篇關於Javascript方法重載的寫法,它是能過另外一個方法來實現的。

看一下這個代碼:

複製代碼 代碼如下:

// addMethod - By John Resig (MIT Licensed)
function addMethod(object, name, fn){
    var old = object[ name ];
    object[ name ] = function(){
        if ( fn.length == arguments.length ){
         return fn.apply( this, arguments );
     }
     else if ( typeof old == 'function' ){
      return old.apply( this, arguments );
  }
}
};

var UserInfo = function(){
    addMethod(this,”find”,function(){
        alert(”沒有參數”);
    });

    addMethod(this,”find”,function(name){
        alert(”傳入的參數是一個,叫 ”+name);
    });

    addMethod(this,”find”,function(name,value){
        alert(”傳入了兩個參數,一個叫 name=”+name+” 一個叫 value=”+value);
    });
};

var userinfo = new UserInfo();
userinfo.find();
userinfo.find('我是誰?');
userinfo.find('某某某','1512412514');


看,這樣一來就簡單了……

聯繫我們

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