Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override Javascript Function Based on Passed Parameters

Is it possible to override a function based on the number of parameters that you are passing into it? For instance:

function abc(name) {
    document.write ('My name is' + name);
}

function abc(name,friend) {
    document.write ('My name is' + name + 'and my best friend\'s name is' + friend);
}

So in the HTML if I just called abc(george) it would use the first version of the function, but if I called abc(george,john) it would use the second version.

There may be other ways to accomplish the example I used, but I'm just wondering if the concept is sound in javascript.

like image 558
Choy Avatar asked Jun 23 '26 10:06

Choy


2 Answers

JavaScript does not support function overloading.

You can, however:

if (typeof friend === "undefined") {
    // do something
} else {
    // do something else
}
like image 164
Quentin Avatar answered Jun 26 '26 01:06

Quentin


Since it wasn't mentioned here I thought I'd throw this out there as well. You could also use the arguments object if your sole intention is to override based on the number of arguments (like you mention in your first sentence):

switch (arguments.length) {
    case 0:
        //Probably error
        break;
    case 1:
        //Do something
        break;
    case 2:
    default: //Fall through to handle case of more parameters
        //Do something else
        break;
}
like image 25
Bob Avatar answered Jun 26 '26 01:06

Bob