Reputation: 9548
Since overloading a function is not allowed, I am trying to find a way to pass values to a function.
In php I resolve in the following way:
// value2 and value3 are optional
function myMethod(value1, value2 = '', value3 = '')
{
// TO DO
}
In Java I can overload the methods:
function myMethod(value1)
{
// TO DO
}
function myMethod(value1, value2)
{
// TO DO
}
In javascript I don't know:
var myAwesomeOptions =
{
'value1' : 'abc',
'value3' : 'def'
}
myMethod(myAwesomeOptions);
function myMethod(options)
{
if (value1 == ???? ) ...
or
switch(options)
....
}
As you can see I am trying to do an overload for a function. How can I pass values to a functions with optional parameters?
Upvotes: 0
Views: 112
Reputation: 3
You can do in the following way:
function myMethod() {
switch (arguments.length) {
case 0:
//TO DO
break;
case 1:
var value1 = arguments[0];
//TO DO
break;
}
}
Upvotes: 0
Reputation: 3118
There's Argument object in JavaScript. For example.
function testme()
{
var first_name=arguments[0] || "John";
var last_name=arguments[1] || "Doe";
alert(first_name);
alert(last_name);
}
testme();
testme("Jane");
So you can use the Argument object to overload functions. Of course you can also pass array or collections too.
Upvotes: 0