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

后端 未结 4 1212
抹茶落季
抹茶落季 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 02:17

    There is no native method overloading in JavaScript. You can create your own, though: http://ejohn.org/blog/javascript-method-overloading/

    (Update 11/5/15: The link seems to be dead, here's the Google Cache version)

    So if you do

    function addClass( class ) { console.log('1 arg'); };
    function addClass( class, duration ) { console.log('2 args'); };
    

    the second one overwrites the first one. So even if you call "addClass(1)", the output will still be "2 args". Same as doing

    someObject.addClass = function(a) {...}
    someObject.addClass = function(a, b) {...}
    

    The first "version" will be lost.

提交回复
热议问题