Javascript中的函数重载 - 最佳实践 [英] Function overloading in Javascript - Best practices

查看:141
本文介绍了Javascript中的函数重载 - 最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Javascript中伪造函数重载的最佳方法是什么?

What is the best way(s) to fake function overloading in Javascript?

我知道不可能像在其他语言中一样重载Javascript中的函数。
如果我需要一个有两次使用的函数 foo(x) foo(x,y,z)这是最佳/首选方式:

I know it is not possible to overload functions in Javascript as in other languages. If I needed a function with two uses foo(x) and foo(x,y,z) which is the best / preferred way:


  1. 首先使用不同的名称

  2. 使用可选参数,如 y = y || 'default'

  3. 使用参数个数

  4. 检查参数类型

  5. 或者如何?

  1. Using different names in the first place
  2. Using optional arguments like y = y || 'default'
  3. Using number of arguments
  4. Checking types of arguments
  5. Or how?


推荐答案

使用参数执行函数重载的最佳方法是不检查参数长度或类型;检查类型只会让你的代码变慢,你可以享受Arrays,nulls,Objects等的乐趣。

The best way to do function overloading with parameters is not to check the argument length or the types; checking the types will just make your code slow and you have the fun of Arrays, nulls, Objects, etc.

大多数开发人员所做的就是将对象作为最后一个对象他们的方法论证。这个对象可以容纳任何东西

What most developers do is tack on an object as the last argument to their methods. This object can hold anything.

function foo(a, b, opts) {
  // ...
  if (opts['test']) { } //if test param exists, do something.. 
}


foo(1, 2, {"method":"add"});
foo(3, 4, {"test":"equals", "bar":"tree"});

然后你可以在你的方法中随意处理它。 [转换,if-else等]

Then you can handle it anyway you want in your method. [Switch, if-else, etc.]

这篇关于Javascript中的函数重载 - 最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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