Do You Use "Fake" Function Overloading In JavaScript?
This question already has an answer here:
In javascript there is a tendency to pass parameters are attributes of an object, ie there is one parameter which is an object, and thus you can specific anything, in any order. With this approach you can check for 'undefined's, and your function can behave according.
If you have rather large behaviour in different cases, you could extend this idea by splitting each case into a seperate function, which is then called by your main 'overloaded' function.
For example:
function a (params) {
// do for a
}
function b () {
// do for b
}
function main (obj) {
if (typeof obj.someparam != 'undefined') {
a(whatever-params);
} else if (typeof obj.someotherparam != 'undefined') {
b(whatever-params);
}
}
You could also use this same approach based on the number parameters, or number of arguements. You can read about using the arguments here.
JavaScript
does not have a support for function overloading. Although it allowed you to pass a variable number of parameter.
You have to check inside function
how many arguments
are passed and what are their types.
This is so common that it is not even noted.
Eg, in JQuery, the on()
method has multiple call signatures:
.on( events [, selector ] [, data ], handler(eventObject) )
.on( events [, selector ] [, data ] )
A call to the first form looks like $('sel').on('click', function(e){/*handler*/})
. A call to the second form looks like $('sel').on({click: function(e){/*click handler*/}, mouseover: function(e){/*mouseover handler*/})
. Note that this demonstrates both "polymorphism" (ie arguments of different types) and "overloading" (ie optional arguments) in the Java/C# terminology.
Keyword arguments (simulated using a single object argument) are also common, eg $.ajax({settings})
.
So yes, this is done all over the place, but your referring to this as "overloading" is a category confusion. JS is neither staticly typed nor do its functions have a fixed number of function arguments. At call time you can supply as many or as few arguments as you want, regardless of what the function declares. You should view the argument list in the function declaration as a shorthand for array destructuring of the arguments
magic variable rather than as a fixed function signature.
The effect on speed is so minimal as to not even be a consideration.
As for when to do this vs when to use a separate function, that is entirely a program clarity and usability concern and probably subject to wide opinion.
链接地址: http://www.djcxy.com/p/51968.html上一篇: 如何在JavaScript中重载?