2017-08-03 56 views
2
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到函数的第二个参数,而无需使用传播算子(...)

+0

您可以发布您的整个代码? – Selvakumar

+0

您必须编写自己的'.bind()'版本。我见过的唯一可以做到的工具是[functional.js](http://functionaljs.com/)库,但该API似乎不再存在。这是一件不寻常的事情。 – Pointy

+1

你看看这个问题https://stackoverflow.com/questions/27699493/javascript-partially-applied-function-how-to-bind-only-the-2nd-parameter –

回答

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);

+1

有趣的做法,我会'交换'一个装饰器,所以它可以像'swap(add).bind(...)'一样使用。 – georg

+0

如果我有'n'个参数并且必须绑定除第一个参数以外的值 –

0

您可以使用以下方式

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的功能

0

这将帮助你什么,你需要

var add = function(a) { 
    return function(b) { 
     return a + b; 
    }; 
} 
var addOne = add(1); 
var result = addOne(4); 
console.log(result); 
0

你可以试试这个

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));

相关问题