Example of method overload in JavaScript

Source: Internet
Author: User

Example of method overload in JavaScript

This article mainly introduces methods in JavaScript to reload instances. This article provides reload instances. For more information, see

 

 

The method overload in. NET is indeed very convenient. Which Javascript can be used?

In javasrt RT, there is no function to overload methods. In the past, many people used to directly reduce the number of parameters and decide how to handle them based on whether the parameter is "undefined" or not, so as to realize the function of reload similar methods.

For example:

 

The Code is as follows:


Var showMessage = function (name, value, id ){
If (id! = "Undefined "){
Alert (name + value + id );
}
Else if (value! = "Undefined "){
Alert (name + value );
}
Else {
Alert (name );
}
}

 

ShowMessage ("Haha ");
ShowMessage ("Haha ","??");
ShowMessage ("Haha ","??", 124124 );

 

Today, I saw an article on Javascript method overload writing on Ajaxian, which can be implemented through another method.

Take a look at this Code:

 

The Code is as follows:


// 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 ("No parameter ");
});

AddMethod (this, "find", function (name ){
Alert ("the input parameter is" + name );
});

AddMethod (this, "find", function (name, value ){
Alert ("two parameters are passed in, one is name =" + name + "and the other is value =" + value );
});
};

Var userinfo = new UserInfo ();
Userinfo. find ();
Userinfo. find ('Who am I? ');
Userinfo. find ('xx, '123 ');


Look, it's easy.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.