0

I have a function:

function bla(param1) {
    // do stuff
}

If I change this to:

function bla(param1, param2) {
    // do stuff
}

Will this affect how the function works? I.e. Can I run this function like this:

function("one");

AND like this:

function ("one", "two");

Will both work in all cases? And if so, will the second parameter just be null?

rockstardev
  • 13,479
  • 39
  • 164
  • 296

3 Answers3

4

No, javascript doesn't know signatures. But you can do something like:

function suchandso(){
  switch (arguments.length) {
     case 1: /*...*/ break;
     case 2: /*...*/ break;
     case n: /*...*/ break;
     default: /*...*/
  }
}
KooiInc
  • 119,216
  • 31
  • 141
  • 177
2

Well, it's hardly what you'd call overloading, but what you're trying to do is allowed:

function f(a,b)
{
    if (b === undefined)//or typeof b === 'undefined'
    {
        console.log('Only param a was passed to me');
        return;//end function
    }
    console.log('Both params were passed');
}

Of course, now if I were to call f with b set to undefined explicitly, the code above won't pick up on that. That's where the arguments object comes in:

function f(a,b)
{
    if (b === undefined && arguments.lenght < 2)//or typeof b === 'undefined'
    {
        console.log('Only param a was passed to me');
        return;//end function
    }
    b = b || 'default value';//fix possibly undefined value
    console.log('Both params were passed');
}

Alternatively, you could use a single argument all the time, and treat it as an object literal:

function f(o)
{
    o = o || {a: 'foo', b: 'bar'};//default object literal
    var a = o.a || 'default a',
    b = o.b || 'default b';
}

You've got tons of options to choose from, I'd say

Elias Van Ootegem
  • 74,482
  • 9
  • 111
  • 149
0

JavaScript does not support method overloading, last function will take precedence over all others. If you wish to use multiple variables, where some may be optional or different you can always do a check in your functions using typeof and determine what set of variables were sent through. Or better, you can use an object literal {} and send varying number of variables in as an argument in key/value pairs, which you can check for and use as you must. For example:

function a(obj) {console.log(obj);}

a({key1: 'value1', key2: 'value2'}); // and so on...
designcise
  • 4,204
  • 1
  • 17
  • 13