Function overloading in Javascript - Best practices

后端 未结 30 2174
难免孤独
难免孤独 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条回答
  •  猫巷女王i
    2020-11-22 03:54

    You can user the 'addMethod' from John Resig. With this method you can "overload" methods based on arguments count.

    // addMethod - By John Resig (MIT Licensed)
    function addMethod(object, name, fn){
        var old = object[ name ];
        object[ name ] = function(){
            if ( fn.length == arguments.length )
                return fn.apply( this, arguments );
            else if ( typeof old == 'function' )
                return old.apply( this, arguments );
        };
    }
    

    I have also created an alternative to this method that uses caching to hold the variations of the function. The differencies are described here

    // addMethod - By Stavros Ioannidis
    function addMethod(obj, name, fn) {
      obj[name] = obj[name] || function() {
        // get the cached method with arguments.length arguments
        var method = obj[name].cache[arguments.length];
    
        // if method exists call it 
        if ( !! method)
          return method.apply(this, arguments);
        else throw new Error("Wrong number of arguments");
      };
    
      // initialize obj[name].cache
      obj[name].cache = obj[name].cache || {};
    
      // Check if a method with the same number of arguments exists  
      if ( !! obj[name].cache[fn.length])
        throw new Error("Cannot define multiple '" + name +
          "' methods with the same number of arguments!");
    
      // cache the method with fn.length arguments
      obj[name].cache[fn.length] = function() {
        return fn.apply(this, arguments);
      };
    }
    

提交回复
热议问题