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

前端 未结 7 1678
时光取名叫无心
时光取名叫无心 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:53

    You could use Function.prototype.bind() for this. It's an ES5 addition.

    In addition to the common usecase of setting a function's context (this value), it can also set partial arguments.

    function out(a, b) {
      document.write(a + " " + b);
    }
    
    function setter(func) {
      return func.bind.apply(func, [window].concat([].slice.call(arguments).slice(1)));
    }
    
    setter(out, "hello")("world");
    setter(out, "hello", "world")();

    My setter function is actually very simple. The longest part is just getting the list of arguments. I'll break up the code like this:

    func.bind.apply(func, [window].concat([].slice.call(arguments).slice(1)))
    func.bind.apply(                                                        )  // need to use apply to pass multiple arguments as an array to bind()
                    func,                                                      // apply needs a context to be run in
                          [window].concat(                                 )   // pass an array of arguments to bind(), starting with window, to be the global context
                                          [].slice.call(arguments).slice(1)    // convert the arguments list to an array, and chop off the initial value
    

    It's supported in these browsers: Chrome 7+, Firefox 4+, IE9+. MDN (linked at the beginning) has a polyfill though.

提交回复
热议问题