javascript tutorial - [Solved-5 Solutions] Function overloading - javascript - java script - javascript array
Problem
What is the best way(s) to fake function overloading in Javascript?
We know it is not possible to overload functions in Javascript as in other languages. If WE needed a function with two uses foo(x) and foo(x,y,z) which is the best / preferred way:
- Using different names in the first place
- Using optional arguments like y = y || 'default'
- Using number of arguments
- Checking types of arguments
- Or how?
Solution 1:
- The best way to do function overloading with parameters is not to check the argument length or the types; checking the types will just make our code slow and we have the fun of Arrays, nulls, Objects, etc.
- What most developers do is tack on an object as the last argument to their methods. This object can hold anything.
Then we can handle it anyway we want in our method. [Switch, if-else, etc.]
Solution 2:
We often do this:
C#:
JavaScript Equivalent:
- This particular example is actually more elegant in javascript than C#. Parameters which are not specified are 'undefined' in javascript, which evaluates to false in an if statement. However, the function definition does not convey the information that p2 and p3 are optional. If we need a lot of overloading, jQuery has decided to use an object as the parameter, for example, jQuery.ajax(options). Weagree with them that this is the most powerful and clearly documentable approach to overloading, but we rarely need more than one or two quick optional parameters.
Solution 3:
There is no real function overloading in JavaScript since it allows to pass any number of parameters of any type. We have to check inside the function how many arguments have been passed and what type they are.
Solution 4:
There are two ways we could approach this better:
- Pass a dictionary (associative array) if we want to leave a lot of flexibility
- Take an object as the argument and use prototype based inheritance to add flexibility.
Solution 5:
The issue is that JavaScript does NOT natively support method overloading. So, if it sees/parses two or more functions with a same names it’ll just consider the last defined function and overwrite the previous ones.
One of the way we think is suitable for most of the case is follows -
Lets say we have method
Instead of overloading method which is not possible in javascript we can define a new method
and then modify the 1st function as follows -