How can I pre-set arguments in JavaScript function call? (Partial Function Application)

前端 未结 7 1691
时光取名叫无心
时光取名叫无心 2020-11-27 11:25

I am trying to write a JavaScript function that will return its first argument(function) with all the rest of its arguments as preset parameters to that function.

So

7条回答
  •  广开言路
    2020-11-27 11:48

    First of all, you need a partial - there is a difference between a partial and a curry - and here is all you need, without a framework:

    function partial(func /*, 0..n args */) {
      var args = Array.prototype.slice.call(arguments, 1);
      return function() {
        var allArguments = args.concat(Array.prototype.slice.call(arguments));
        return func.apply(this, allArguments);
      };
    }
    

    Now, using your example, you can do exactly what you are after:

    partial(out, "hello")("world");
    partial(out, "hello", "world")();
    
    // and here is my own extended example
    var sayHelloTo = partial(out, "Hello");
    sayHelloTo("World");
    sayHelloTo("Alex");
    

    The partial() function could be used to implement, but is not currying. Here is a quote from a blog post on the difference:

    Where partial application takes a function and from it builds a function which takes fewer arguments, currying builds functions which take multiple arguments by composition of functions which each take a single argument.

    Hope that helps.

提交回复
热议问题