How to bind function arguments without binding this?

前端 未结 15 935
爱一瞬间的悲伤
爱一瞬间的悲伤 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:46

    An anonymous user posted this additional info:

    Building on what has already been provided in this post -- the most elegant solution I've seen is to Curry your arguments and context:

    function Class(a, b, c, d){
        console.log('@Class #this', this, a, b, c, d);
    }
    
    function Context(name){
        console.log('@Context', this, name);
        this.name = name;
    }
    
    var context1 = new Context('One');
    var context2 = new Context('Two');
    
    function curryArguments(fn) {
        var args = Array.prototype.slice.call(arguments, 1);
        return function bindContext() {
          var additional = Array.prototype.slice.call(arguments, 0);
          return fn.apply(this, args.concat(additional));
        };
    }
    
    var bindContext = curryArguments(Class, 'A', 'B');
    
    bindContext.apply(context1, ['C', 'D']);
    bindContext.apply(context2, ['Y', 'Z']);
    

提交回复
热议问题