var add = function(a, b) {
return a + b;
}
var addOne =add.bind(null,1);
var result = addOne(4);
console.log(result);
這裏的綁定的值是1,b是4僅結合第二個參數javascript函數
如何分配的結合值即)1到函數的第二個參數,而無需使用傳播算子(...)
var add = function(a, b) {
return a + b;
}
var addOne =add.bind(null,1);
var result = addOne(4);
console.log(result);
這裏的綁定的值是1,b是4僅結合第二個參數javascript函數
如何分配的結合值即)1到函數的第二個參數,而無需使用傳播算子(...)
你可以採取交換功能與結合的最終功能。
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);
有趣的做法,我會'交換'一個裝飾器,所以它可以像'swap(add).bind(...)'一樣使用。 – georg
如果我有'n'個參數並且必須綁定除第一個參數以外的值 –
您可以使用以下方式
var add = function(x){
return function(y){
return x+y;
}
}
add(2)(3); // gives 5
var add5 = add(5);
add5(10); // gives 15
這裏ADD5()將集合X = 5的功能
這將幫助你什麼,你需要
var add = function(a) {
return function(b) {
return a + b;
};
}
var addOne = add(1);
var result = addOne(4);
console.log(result);
你可以試試這個
function add (n) {
var func = function (x) {
if(typeof x==="undefined"){
x=0;
}
return add (n + x);
};
func.valueOf = func.toString = function() {
return n;
};
return func;
}
console.log(+add(1)(2));
console.log(+add(1)(2)(3));
console.log(+add(1)(2)(5)(8));
您可以發佈您的整個代碼? – Selvakumar
您必須編寫自己的'.bind()'版本。我見過的唯一可以做到的工具是[functional.js](http://functionaljs.com/)庫,但該API似乎不再存在。這是一件不尋常的事情。 – Pointy
你看看這個問題https://stackoverflow.com/questions/27699493/javascript-partially-applied-function-how-to-bind-only-the-2nd-parameter –