Method overload instance _javascript techniques in JavaScript

Source: Internet
Author: User

. NET inside the method overload is indeed very convenient, which JavaScript can also do what?

Javasciprt There is no way to overload the function, many people before the practice may be directly less pass parameters, and then in accordance with the parameters are not defined as "undefined" to determine how to deal with, so as to achieve a similar method overload functionality.

For example:

Copy Code code 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, on Ajaxian, I saw an article on the JavaScript method overload, which can be done in another way.

Take a look at this code:

Copy Code code 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 parameters");
});

Addmethod (this, ' Find ', function (name) {
Alert ("Incoming parameter is one, called" +name);
});

Addmethod (this, ' Find ', function (name,value) {
Alert ("passed in two parameters, one is called name=" +name+ "one is called value=" +value);
});
};

var userinfo = new UserInfo ();
Userinfo.find ();
Userinfo.find (' Who am I? ');
Userinfo.find (' So-and-so ', ' 1512412514 ');


Look, this is simple ...

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.