Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function overloading in Javascript - Best practices [closed]

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?
like image 984
hamdiakoguz Avatar asked Jan 19 '09 00:01

hamdiakoguz


People also ask

Is function overloading allowed in JavaScript?

JavaScript does not support function overloading natively. If we will add functions with the same name and different arguments, it considers the last defined function.

Is function overloading good practice?

You need to be careful while overloading a method in Java, especially after the introduction of autoboxing in Java 5. Poorly overloaded method not only adds confusion among developers who use that but also they are error-prone and leaves your program at compiler's mercy to select proper method.

What are the restrictions on overloading function?

Function declarations that have equivalent parameter declarations. These declarations are not allowed because they would be declaring the same function. Function declarations with parameters that differ only by the use of typedef names that represent the same type.

How can overloading a function be overcome?

In C++ we can overcome this by making use of using A::get but in SV how to avoid function hiding and access the parent class function get()? there is no overloading in system verilog. So, just use different names for the functions.


1 Answers

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.]

like image 135
epascarello Avatar answered Sep 23 '22 10:09

epascarello