var add = function(a, b) {
return a + b;
}
var addOne =add.bind(null,1);
var result = addOne(4);
console.log(result);
此处a的绑定(bind)值为1,b为4。
如何在不使用扩展运算符(...)的情况下将绑定(bind)值 i.e)1 分配给函数的第二个参数
最佳答案
您可以使用绑定(bind)最终函数的交换函数。
var add = function (a, b) { console.log(a, b); return a + b; },
swap = function (a, b) { return this(b, a); },
addOne = swap.bind(add, 1),
result = addOne(4);
console.log(result);
带有装饰器,如georg建议。
var add = function (a, b) { console.log(a, b); return a + b; },
swap = function (f) { return function (b, a) { return f.call(this, a, b) }; },
addOne = swap(add).bind(null, 1),
result = addOne(4);
console.log(result);
您可以使用 arguments
用于重新排序参数的对象。
var add = function (a, b, c, d, e) {
console.log(a, b, c, d, e);
return a + b + c + d + e;
},
swap = function (f) {
return function () {
var arg = Array.apply(null, arguments);
return f.apply(this, [arg.pop()].concat(arg));
};
},
four = swap(add).bind(null, 2, 3, 4, 5),
result = four(1);
console.log(result);
关于javascript - 仅将第二个参数绑定(bind)到 javascript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45485140/