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?

4
  • 3
    Did you try it though? Commented Jun 10, 2013 at 6:17
  • 1
    stackoverflow.com/questions/10855908/… Commented Jun 10, 2013 at 6:18
  • If they are at the same scope, the last declaration will prevail (as if the first one never existed). Commented Jun 10, 2013 at 6:21
  • John Resig implemented method overloading, using the function.length property: ejohn.org/blog/javascript-method-overloading Commented Jun 10, 2013 at 6:34

3 Answers 3

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: /*...*/
  }
}
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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...

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.