1

I have a jQuery function that needs parameters passed on to it. Let's say it's:

function myFunc(foo, moo) {
   // Do something
}

However, in one page, there are 2 instances wherein this function is used with 2 different sets of parameters like so:

myFunc(foo1, moo1);
myFunc(foo2, moo2);

Let's say I have more than 2 different sets of parameters... do I always re-declare the function and then the parameters (like below) or is there a shorter way of doing it? And is it even correct?

myFunc(foo1, moo1);
myFunc(foo2, moo2);
myFunc(foo3, moo3);
...etc...
catandmouse
  • 11,309
  • 23
  • 92
  • 150
  • 1
    Rather than redeclaring, you can pass the params as an array. And do necessary logic in your func code. `myfunc(options=[])` – Jeremy Rajan Mar 01 '16 at 06:51
  • You just have to declare function only once..you can call multiple time...if your parameters are in sequence then you can for use loop for call function – Divyesh Savaliya Mar 01 '16 at 06:52

2 Answers2

0

You can use arguments object of the Javascript functions. This object contain an array of parametes passed to that function. So you can define the function once and call the function with any number of parameters:

function myFunc() {
 for(i=0; i<arguments.length; i++) {
  console.log(arguments[i]);
 }
}

And you can call this function as below:

myFunc(foo);
myFunc(foo, moo);
Shwetha
  • 903
  • 8
  • 15
0

What you're referring to is know as Method Overloading in Java. There is no one hard and fast rule of handling it in Javascript.

This is a similar question which addresses your question: Function overloading in Javascript - Best practices

Hope this helps.

Community
  • 1
  • 1
Sukrit
  • 308
  • 2
  • 12