I was trying to write some javascript function and realised that
function testFunction(input_1, input_2, input_3) {
alert("alert");
}
however when i call the function like this:
<input type="button" value="click" onclick="testFunction("1", "2")">
why will it still work even with just two parameters?
8 Answers 8
You can call a Javascript function with any number of parameters, regardless of the function's definition.
Any named parameters that weren't passed will be undefined.
Extra parameters can be accessed through the arguments array-like object.
3 Comments
null or false or any other value.null.It doesn't actually matter how many parameters you are providing. the function interprets them and creates the arguments object (which acts as an array of parameters).
Here's an example:
function sum(){
if(arguments.length === 0)
return 0;
if(arguments.length === 1)
return arguments[0];
return arguments[0] + sum.apply(this, [].slice.call(arguments, 1));
}
It's not the most efficient solution, but it provides a short peak at how functions can handle arguments.
Comments
Because javascript treats your parameters as an array; if you never go beyond the second item, it never notices an argument is missing.
1 Comment
arguments array. And named parameters in function declarations are just pointers to members of argumentsJavascript does not support Method overloading hence method will be execute in order of their occurence irrelevant of arguments passed Because javascript has no type checking on arguments or required qty of arguments, you can just have one implementation of testFunction() that can adapt to what arguments were passed to it by checking the type, presence or quantity of arguments..
Comments
The third parameter can be optional and will have a (削除) null (削除ここまで) undefined default value.
If you explicitly want to have a required parameter, you need to require it via code inside the function.
5 Comments
undefined.undefined and throwing an error. Depending on the acceptable values, you might able to just do if(parameter).Because Parameters are optional
Some Reading: http://www.tipstrs.com/tip/354/Using-optional-parameters-in-Javascript-functions
Comments
Javascript is a very dynamic language and will assume a value of "undefined" for any parameters not passed a value.
Comments
Try using the below code
var CVH = {
createFunction: function (validationFunction, extParamData, extParamData1) {
var originalFunction = validationFunction;
var extParam = extParamData;
var extParam1 = extParamData1;
return function (src, args) {
// Proxy the call...
return originalFunction(src, args, extParam, extParam1);
}
}
}
function testFunction(input_1, input_2, input_3) {
alert("alert");
}
and you can call this function as below
<input type="button" value="click" onclick="CVH.createFunction(testFunction('1', '2'),'3','4')">
onclick="testFunction("1", "2")">should beonclick="testFunction('1', '2')">. Otherwise you'll get errors.