Function overloading in Javascript - Best practices

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

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:

    • Using different names in the first place
    • Using optional arguments like y = y || default
    • Using number of arguments
    • Checking types of arguments
    • Or how?

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) {

}


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

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/456177/function-overloading-in-javascript-best-practices

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils