Saturday 8 December 2018

Function overloading in Javascript - Best practices



What is the best way(s) to fake function overloading in Javascript?



I know it is not possible to overload functions in Javascript as in other languages.
If I needed a function with two uses foo(x) and foo(x,y,z) which is the best / preferred way:





  1. Using different names in the first place

  2. Using optional arguments like y = y || 'default'

  3. Using number of arguments

  4. Checking types of arguments

  5. Or how?


Answer



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 your code slow and you 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.



function foo(a, b, opts) {
// ...
if (opts['test']) { } //if test param exists, do something..
}


foo(1, 2, {"method":"add"});

foo(3, 4, {"test":"equals", "bar":"tree"});


Then you can handle it anyway you want in your method. [Switch, if-else, etc.]


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...