简体   繁体   English

基于传递参数覆盖Javascript函数

[英]Override Javascript Function Based on Passed Parameters

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. 所以在HTML中,如果我刚刚调用abc(george)它将使用该函数的第一个版本,但如果我调用abc(george,john)它将使用第二个版本。

There may be other ways to accomplish the example I used, but I'm just wondering if the concept is sound in javascript. 可能还有其他方法来完成我使用的示例,但我只是想知道这个概念在javascript中是否合理。

JavaScript does not support function overloading. JavaScript不支持函数重载。

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): 如果您的唯一意图是根据参数的数量覆盖(如您在第一句中提到的那样),您也可以使用arguments对象:

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. 是的,确实,JavaScript默认执行此操作。 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. 不,原生Javascript不允许重载功能。

A Workaround is just don't send that parameter. 解决方法是不发送该参数。 You will get undefined in the last parameter. 您将在最后一个参数中得到未定义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM