You cannot have two functions with the same name in javascript. Whichever is defined last will take precedence.
You can, however, test arguments at run-time and change your behavior depending upon what was passed to the function. This is a common design pattern and is used a lot by libraries like jQuery.
For example, in jQuery, there's a function .animate()
which takes 1-4 arguments passed in a couple different ways:
.animate( properties [, duration ] [, easing ] [, complete ] )
.animate( properties, options )
Only the properties argument is required. All the other arguments are optional and jQuery tests for their existence by checking to see what was passed and what type it was and figures out which form you are using and which arguments are present.
Or, another example:
.toggle( [duration ] [, complete ] )
.toggle( options )
.toggle( duration [, easing ] [, complete ] )
.toggle( showOrHide )
All of these forms are implemented with the same function using run-time checking of argument types and existence. Here's an idea how you could implement the four forms of .toggle()
.
function toggle(duration, easing, complete) {
if (typeof duration === "boolean") {
// toggle(bool) form
// and the showOrHide arg is in the duration argument
} else if (typeof duration === "object") {
// toggle(options) form
// and the options object is in the duration argument
} else {
// toggle(duration, complete)
// toggle(duration, easing, complete)
// if no 3rd arg, then easing must have been left out
if (!complete) {
// completion function is in the 2nd arg to move it
// to the proper named arg
complete = easing
// easing wasn't passed, give it a default value
easing = "linear";
}
// process it as toggle(duration, easing, complete)
// here
}
}