繁体   English   中英

从右到左局部应用?

[英]Partial application right to left?

在JS中使用bind时,可以使用预定义的参数创建函数,例如:

var add = function (a, b) {
    return a + b;
};
var addToThree = add.bind(null, 3);

但是,如果我想预定义第二个,第三个等参数,而不是第一个,我该怎么做呢?

你可以做

var add = function (a, b) {
    b = b || 5;
    return a + b;
};

ES6中,可以很容易地使用默认参数

var add = function (a, b=5) {
    return a + b;
};

并像add(3);一样调用它add(3);

在ES2015中,您可以执行以下操作:

 const partial = fn => (...pargs) => (...args) => fn.apply(null, [...pargs, ...args]); const partialRight = fn => (...pargs) => (...args) => fn.apply(null, [...args, ...pargs.reverse()]); const myFunc = (one, two, three, four) => { console.log(one); console.log(two); console.log(three); console.log(four); }; const myFuncPartial = partial(myFunc)('1'); const myFuncPartialRight = partialRight(myFuncPartial)('4', '3'); myFuncPartialRight('2'); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM