Override Javascript function based on passed parameters

Is it possible to override a function based on the number of parameters you pass 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\ name is' + friend);
}

      

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

There may be other ways to follow through with the example I used, but I'm just wondering if the concept sounds like javascript.

+2


a source to share


5 answers


JavaScript does not support function overloading.

However, you can:



if (typeof friend === "undefined") {
    // do something
} else {
    // do something else
}

      

+10


a source


Since it wasn't mentioned here, I thought I'd throw it away too. You can also use the arguments object if your only intention is to override it based on the number of arguments (as you mentioned in the 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;
}

      

+4


a source


Yes, 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);

      

+2


a source


You can leave the required argument and pass the remainder in the 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)
      ...
}

      

+1


a source


No, native Javascript does not allow function overloading.

The workaround simply doesn't send this parameter. You will get undefined in the last parameter.

0


a source







All Articles