0

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?

2
  • 1
    possible duplicate of Function overloading in Javascript - Best practices Commented Aug 17, 2013 at 7:53
  • It's not a complete answer, because I don't know how to switch between values. I know how to pass an array, but how to handle them? Commented Aug 17, 2013 at 7:55

3 Answers 3

2

Chech this link..

Object.prototype.toString.call(vArg) === "[object Array]";

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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;
 }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.