Does JS support two functions with the same name and different parameters ?
function f1(a, b) { // a and b are numbers } function f1(a, b, c) { // a is a string //b and c are numbers }
Can I use those JS function for IE7, FF, Opera with no problem?
Arguments are Passed by Value The parameters, in a function call, are the function's arguments. JavaScript arguments are passed by value: The function only gets to know the values, not the argument's locations. If a function changes an argument's value, it does not change the parameter's original value.
A JavaScript function can have any number of parameters. The 3 functions above were called with the same number of arguments as the number of parameters. But you can call a function with fewer arguments than the number of parameters.
function ceshi(test,lyj,param1,parm2){ console. log(arguments) } var params = [2,3]; ceshi(eval('2,3'));
These parameters are just like variables except that the values of these variables are defined when we call the function and are not assigned values within the function itself. Parameters are specified within the pair of parentheses in the function definition, separated by commas.
JavaScript doesn't support what you would call in other languages method overloading, but there are multiple workarounds, like using the arguments
object, to check with how many arguments a function has been invoked:
function f1(a, b, c) { if (arguments.length == 2) { // f1 called with two arguments } else if (arguments.length == 3) { // f1 called with three arguments } }
Additionally you could type-check your arguments, for Number and String primitives is safe to use the typeof
operator:
function f1(a, b, c) { if (typeof a == 'number' && typeof b == 'number') { // a and b are numbers } else if (typeof a == 'string' && typeof b == 'number' && typeof c == 'number') { // a is a string, b and c are numbers } }
And there are much more sophisticated techniques like the one in the following article, that takes advantage of some JavaScript language features like closures, function application, etc, to mimic method overloading:
No, you can't use function overloading in JS.
But, you can declare just the version with 3 parameters, and then check whether the third argument === undefined
, and provide differentiated behaviour on that basis.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With