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

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

    Using Javascript's apply(), you can modify the function prototype

    Function.prototype.pass = function() {
        var args = arguments,
            func = this;
        return function() {
            func.apply(this, args);
        }
    };
    

    You can then call it as out.pass('hello','world')

    apply takes an array for 2nd argument/parameter.

    arguments is property available inside function which contains all parameters in array like structure.

    One other common way to do this is to use bind

    loadedFunc = func.bind(this, v1, v2, v3);

    then

    loadedFunc() === this.func(v1,v2,v3);

    this kinda suffice, even though little ugly.

提交回复
热议问题