JavaScript partially applied function - How to bind only the 2nd parameter?

后端 未结 4 1250
忘掉有多难
忘掉有多难 2020-12-23 19:59

Sorry if I\'m missing something obvious, but I can\'t figure out how to bind a specific (nth) argument of a function in javascript. Most of my functional programming I\'ve

4条回答
  •  执念已碎
    2020-12-23 20:40

    you can try this:

    Function.prototype.bindThemAll = function bindThemAll(thisArg, ...boundArgs) 
      (boundArgs.fn = this, function(...args) boundArgs.fn.call(thisArg || this, ...boundArgs.map((el) => el || args.shift()), ...args));
    
    function fn() console.log("fn:", arguments.callee, "this:", this, "args:", arguments)
    
    var x = {a: 5};
    
    var bfn = fn.bindThemAll(x, null, 2)
    bfn(1,3)
    x.bfn = fn.bindThemAll(null, null, 2)
    x.bfn(1,3)

    bound arguments with null or undefined will be replaced with the function arguments in order, the remaining arguments will be appended to the end. an object will be used if it is bound otherwise the current this will be used...

    see console for results!

提交回复
热议问题