Function overloading in Javascript - Best practices

后端 未结 30 2172
难免孤独
难免孤独 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:59

    Function overloading in Javascript:

    Function overloading is the ability of a programming language to create multiple functions of the same name with different implementations. when an overloaded function is called it will run function a specific implementation of that function appropriate to the context of the call. This context is usually the amount of arguments is receives, and it allows one function call to behave differently depending on context.

    Javascript doesn't have built-in function overloading. However, this behaviour can be emulated in many ways. Here is a convenient simple one:

    function sayHi(a, b) {
      console.log('hi there ' + a);
      if (b) { console.log('and ' + b) } // if the parameter is present, execute the block
    }
    
    sayHi('Frank', 'Willem');

    In scenarios where you don't know how many arguments you will be getting you can use the rest operator which is three dots .... It will convert the remainder of the arguments into an array. Beware of browser compatibilty though. Here is an example:

    function foo (a, ...b) {
      console.log(b);
    }
    
    foo(1,2,3,4);
    foo(1,2);

提交回复
热议问题