Override Javascript Function Based on Passed Parameters

风流意气都作罢 提交于 2019-12-04 17:43:44

JavaScript does not support function overloading.

You can, however:

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

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;
}

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

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!