How to bind function arguments without binding this?

前端 未结 15 924
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-30 07:25

In Javascript, how can I bind arguments to a function without binding the this parameter?

For example:

//Example function.
var c = funct         


        
15条回答
  •  爱一瞬间的悲伤
    2020-11-30 07:36

    It's a bit hard to tell exactly what you ultimately want to do because the example is sort of arbitrary, but you may want to look into partials (or currying): http://jsbin.com/ifoqoj/1/edit

    Function.prototype.partial = function(){
      var fn = this, args = Array.prototype.slice.call(arguments);
      return function(){
        var arg = 0;
        for ( var i = 0; i < args.length && arg < arguments.length; i++ )
          if ( args[i] === undefined )
            args[i] = arguments[arg++];
        return fn.apply(this, args);
      };
    };
    
    var c = function(a, b, c, callback) {
      console.log( a, b, c, callback )
    };
    
    var b = c.partial(1, 2, 3, undefined);
    
    b(function(){})
    

    Link to John Resig's article: http://ejohn.org/blog/partial-functions-in-javascript/

提交回复
热议问题