Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
286 views
in Technique[技术] by (71.8m points)

javascript - Javascript中的函数重载-最佳做法(Function overloading in Javascript - Best practices)

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

(用JavaScript伪造函数重载的最佳方法是什么?)

I know it is not possible to overload functions in Javascript as in other languages.

(我知道不可能像其他语言一样重载Javascript中的函数。)

If I needed a function with two uses foo(x) and foo(x,y,z) which is the best / preferred way:

(如果我需要两个函数一起使用foo(x)foo(x,y,z) ,这是最佳/首选方式:)

  1. Using different names in the first place

    (首先使用不同的名称)

  2. Using optional arguments like y = y || 'default'

    (使用可选参数,例如y = y || 'default') y = y || 'default'

  3. Using number of arguments

    (使用参数数量)

  4. Checking types of arguments

    (检查参数类型)

  5. Or how?

    (或如何?)

  ask by hamdiakoguz translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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等。])


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...