2

Is it possible to override a function based on the number of parameters that you are passing into it? For instance:

function abc(name) {
    document.write ('My name is' + name);
}

function abc(name,friend) {
    document.write ('My name is' + name + 'and my best friend\'s name is' + friend);
}

So in the HTML if I just called abc(george) it would use the first version of the function, but if I called abc(george,john) it would use the second version.

There may be other ways to accomplish the example I used, but I'm just wondering if the concept is sound in javascript.

5 Answers 5

10

JavaScript does not support function overloading.

You can, however:

if (typeof friend === "undefined") {
    // do something
} else {
    // do something else
}
Sign up to request clarification or add additional context in comments.

4 Comments

Is this a standard way of implementing method overloading in JavaScript?
Thanks, I didn't know what the term was for that sort of thing (no wonder my Google search results sucked!).
Also, I notice that you're using a strict equality in your example. Would it matter if friend were an integer or string when I actually do pass it? So abc(george,5) instead of abc(george,john) or abc(george,"5").
@George, the strict equality doesn't really matters in this case, because the typeof operator will always return a string, even for host objects.
4

Since it wasn't mentioned here I thought I'd throw this out there as well. You could also use the arguments object if your sole intention is to override based on the number of arguments (like you mention in your first sentence):

switch (arguments.length) {
    case 0:
        //Probably error
        break;
    case 1:
        //Do something
        break;
    case 2:
    default: //Fall through to handle case of more parameters
        //Do something else
        break;
}

Comments

2

Yup, indeed, JavaScript does this by default. If you have a function:

 function addInts(a, b, c)
 {
      if(c != undefined)
         return a + b + c;
      else
         return a + b;
 }

 addInts(3, 4);
 addInts(3, 4, 5);

Comments

2

You can leave the required argument and pass the remainder in an object

abc(name);
abc(name, {"friend": friend});
abc(name, {"friend": friend, "age": 21});

function abc(name, extra) {
   if (!extra.friend) 
      alert("no mates");
   for (var key in extra)
      ...
}

Comments

0

No, Native Javascript does not allow to overload functions.

A Workaround is just don't send that parameter. You will get undefined in the last parameter.

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.