How to detect a JavaScript function with a certain signature has been registered?

后端 未结 4 1163
抹茶落季
抹茶落季 2021-02-02 01:38

Say you have two functions with the following signatures:

  1. addClass( class )
  2. addClass( class, duration )
4条回答
  •  孤独总比滥情好
    2021-02-02 01:51

    It isn't very difficult to achieve, but Resig's method isn't up to much, as it only checks for arguments length, which is only tangentially related to real call signatures.

    Johannes method is actually method overriding not multiple call signatures, and anyway will fail in JS Strict mode where multiple function declaration of the same name are forbidden.

    To implement properly you'll need to implement it via call forwarding, wrapping each call signature in a type/existence check:

    function myFunction(arg1, arg2, arg3){
      switch(true){
        case arg1 instanceof someObject:
            myFunction_signature1.apply(this, arguments);
            break;
        case typeof arg1 === "string":
            myFunction_signature2.apply(this, arguments);
            break;
        }
    }
    

    It gets a little more complex when some params are optional as well.

提交回复
热议问题