Function overloading in Javascript - Best practices

后端 未结 30 2173
难免孤独
难免孤独 2020-11-22 03:33

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

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

30条回答
  •  梦谈多话
    2020-11-22 03:53

    The correct answer is THERE IS NO OVERLOADING IN JAVASCRIPT.

    Checking / Switching inside the function is not OVERLOADING.

    The concept of overloading: In some programming languages, function overloading or method overloading is the ability to create multiple methods of the same name with different implementations. Calls to an overloaded function will run a specific implementation of that function appropriate to the context of the call, allowing one function call to perform different tasks depending on context.

    For example, doTask() and doTask(object O) are overloaded methods. To call the latter, an object must be passed as a parameter, whereas the former does not require a parameter, and is called with an empty parameter field. A common error would be to assign a default value to the object in the second method, which would result in an ambiguous call error, as the compiler wouldn't know which of the two methods to use.

    https://en.wikipedia.org/wiki/Function_overloading

    All suggested implementations are great, but truth to be told, there is no native implementation for JavaScript.

提交回复
热议问题