Skip to main content
edited tags
Link
Wicket
  • 39.3k
  • 9
  • 81
  • 201
Question Protected by Tushar Gupta - curioustushar
Source Link
Travis J
  • 82.5k
  • 43
  • 212
  • 280

How to overload functions in javascript?

Classical (non-js) approach to overloading:

function myFunc(){
 //code
}

function myFunc(overloaded){
 //other code
}

Javascript wont let more than one function be defined with the same name. As such, things like this show up:

function myFunc(options){
 if(options["overloaded"]){
  //code
 }
}

Is there a better workaround for function overloading in javascript other than passing an object with the overloads in it?

Passing in overloads can quickly cause a function to become too verbose because each possible overload would then need a conditional statement. Using functions to accomplish the //code inside of those conditional statements can cause tricky situations with scopes.