帮助JS和函数参数 [英] Help with JS and functions parameters

查看:95
本文介绍了帮助JS和函数参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Does JS support two functions with the same name and different parameters ?

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

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

我可以使用这些JS吗? IE7,FF,Opera的功能没有问题?

Can I use those JS function for IE7, FF, Opera with no problem?

推荐答案

JavaScript不支持你在其他语言中调用的内容方法重载,但有多种解决方法,例如使用 arguments object,检查函数被调用了多少个参数:

JavaScript doesn't support what you would call in other languages method overloading, but there are multiple workarounds, like using the arguments object, to check with how many arguments a function has been invoked:

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

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

Additionally you could type-check your arguments, for Number and String primitives is safe to use the typeof operator:

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

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

And there are much more sophisticated techniques like the one in the following article, that takes advantage of some JavaScript language features like closures, function application, etc, to mimic method overloading:

  • JavaScript method overloading

这篇关于帮助JS和函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆