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

后端 未结 4 1258
忘掉有多难
忘掉有多难 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:38

    You can use lodash's _.bind to achieve this:

    var add = function(a, b) {
      document.write(a + b);
    };
    
    // Bind to first parameter (Nothing special here)
    var bound = _.bind(add, null, 3);
    bound(4);
    // → 7
    
    // Bind to second parameter by skipping the first one with "_"
    var bound = _.bind(add, null, _, 4);
    bound(3);
    // → 7

    I am usually against libraries and prefer coding my own utility functions, but an exception can easily be made for lodash. I would highly suggest you check its documentation whenever you have a "This must be in the language somewhere!" moment. It fills in a lot of blanks in JavaScript.

提交回复
热议问题