帮助JS和函数参数

Ali*_*ile 21 javascript

JS是否支持具有相同名称和不同参数的两个函数?

function f1(a, b)
{
// a and b are numbers
}

function f1(a, b, c)
{
// a is a string
//b and c are numbers
}
Run Code Online (Sandbox Code Playgroud)

我可以使用那些JS函数用于IE7,FF,Opera没有问题吗?

CMS*_*CMS 34

JavaScript不支持您在其他语言方法重载中调用的内容,但是有多种解决方法(如使用该arguments对象)来检查调用函数的参数数量:

function f1(a, b, c) {
  if (arguments.length == 2) {
    // f1 called with two arguments
  } else if (arguments.length == 3) {
    // f1 called with three arguments
  }
}
Run Code Online (Sandbox Code Playgroud)

另外,您可以键入 - 检查您的参数,对于Number和String 原语,使用typeof运算符是安全的:

function f1(a, b, c) {
  if (typeof a == 'number' && typeof b == 'number') {
    // a and b are numbers
  } else if (typeof a == 'string' && typeof b == 'number' &&
             typeof c == 'number') {
    // a is a string, b and c are numbers
  }
}
Run Code Online (Sandbox Code Playgroud)

还有更复杂的技术,如下一篇文章中的那些,利用一些JavaScript语言功能,如闭包,函数应用程序等,来模仿方法重载:


Chr*_*ung 7

不,你不能在JS中使用函数重载.

但是,您可以只声明具有3个参数的版本,然后检查是否存在第三个参数=== undefined,并在此基础上提供差异化​​行为.