2016-02-06 15 views
1

The closest I've seen is this, but it doesn't really help me since I need to bind some parameters for later use with setIntervalJavascript:參數解壓在function.prototype.bind()中?

更具體地:

[in] var d = function(l, m) { 
     console.log(l); 
     console.log(m); 
    } 
[in] d.apply(window, [1,2]) 
[out] 1 
[out] 2 
[out-return-value] undefined 
[in] d.bind(window, [1,2])() 
[out] [1, 2] 
[out] undefined 
[out-return-value] undefined 

如可以看到的,陣列是解壓與.apply(),但不與.bind()。有沒有辦法用.bind()解開參數?

+1

好像我之前回答了這樣一個問題:P –

回答

2

.bind只是另一個功能。與.apply打電話,如果你想用的參數數組來調用它:

var bound = d.bind.apply(d, [window, 1, 2]); 
// If the `this` value is known, but the arguments is an array, concat: 
// var bound = d.bind.apply(d, [window].concat(args)) 
2

試試這個。

Function.prototype.bindArray(ctx, array) { 
    if (array && array.length && array.pop && array.length > 0) { 
    var v = array.pop(); 
    return this.bindArray(ctx, array).bind(ctx, v); 
    } 
    else return this; 
}; 

它會反覆在array每個值綁定。

這樣使用它:

var d = function(l, m) { 
    console.log(l); 
    console.log(m); 
}; 
var c = d.bindArray(null, [1,2]); 
c(); // 1 2 

參看下面@ Felix的答案。這甚至很酷。

+0

我真的很喜歡這一點。非常優雅 - 很好! –

+0

問題:因爲我認爲我找到了一個沒有迭代的解決方案,這是否也可以工作,或者如果不是的話,爲什麼? ' 'return this.bind.apply(this,array);' '}' – 13steinj

+0

這似乎過於複雜(對於任務)並且創建了不必要的中間函數對象。 –