Saturday, 3 September 2016

c# - Do You Use "Fake" Function Overloading In JavaScript?




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.


Answer



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.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...