Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do You Use "Fake" Function Overloading In JavaScript? [duplicate]

In C# I might have an overloaded function like so:

public string OverLoad(string str1)                  {return str1;}
public string OverLoad(string str1, string str2)     {return str1+str2;}

I know that JavaScript does not have built in support for overloaded functions, but does anyone work around this to still achieve overloaded function capabilities?

I am curious about:

1.) Effect on speed

2.) Reasons to use different function names vs. overloads

It seems you could check for the parameters being undefined or not and "fake" the capability in JavaScript. To me the ease of changing functions by only changing the number of parameters would be quite an advantage.

like image 967
Fleming Slone Avatar asked Feb 17 '23 23:02

Fleming Slone


2 Answers

In javascript there is a tendency to pass parameters are attributes of an object, ie there is one parameter which is an object, and thus you can specific anything, in any order. With this approach you can check for 'undefined's, and your function can behave according.

If you have rather large behaviour in different cases, you could extend this idea by splitting each case into a seperate function, which is then called by your main 'overloaded' function.

For example:

function a (params) {
    // do for a
}
function b () {
    // do for b
}
function main (obj) {
    if (typeof obj.someparam != 'undefined') {
        a(whatever-params);
    } else if (typeof obj.someotherparam != 'undefined') {
        b(whatever-params);
    }
}

You could also use this same approach based on the number parameters, or number of arguements. You can read about using the arguments here.

like image 125
Nick Mitchinson Avatar answered Mar 01 '23 23:03

Nick Mitchinson


JavaScript does not have a support for function overloading. Although it allowed you to pass a variable number of parameter.

You have to check inside function how many arguments are passed and what are their types.

like image 41
Parimal Raj Avatar answered Mar 02 '23 00:03

Parimal Raj