Help with JS and functions parameters

后端 未结 6 1755
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-31 19:26

Does JS support two functions with the same name and different parameters ?

function f1(a, b)
{
// a and b are numbers
}

function f1(a, b, c)
{
// a is a string         


        
6条回答
  •  故里飘歌
    2021-01-31 19:34

    JavaScript doesn't support what you would call in other languages method overloading, but there are multiple workarounds, like using the arguments object, to check with how many arguments a function has been invoked:

    function f1(a, b, c) {
      if (arguments.length == 2) {
        // f1 called with two arguments
      } else if (arguments.length == 3) {
        // f1 called with three arguments
      }
    }
    

    Additionally you could type-check your arguments, for Number and String primitives is safe to use the typeof operator:

    function f1(a, b, c) {
      if (typeof a == 'number' && typeof b == 'number') {
        // a and b are numbers
      } else if (typeof a == 'string' && typeof b == 'number' &&
                 typeof c == 'number') {
        // a is a string, b and c are numbers
      }
    }
    

    And there are much more sophisticated techniques like the one in the following article, that takes advantage of some JavaScript language features like closures, function application, etc, to mimic method overloading:

    • JavaScript method overloading

提交回复
热议问题