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"});
Then you can handle it anyway you want in your method.
(然后,您可以在方法中以任何方式处理它。)
[Switch, if-else, etc.] ([切换,if-else等。])
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…