2016-03-06 56 views
0

這些代碼被張貼在代碼審查前兩天:JavaScript的綁定()與咖喱。這些代碼如何工作?

function curry(f, self) { 
    return function() { 
    if (arguments.length == f.length) { 
     return f.apply(self, arguments); 
    } 
    arguments = Array.prototype.slice.call(arguments); 

    return curry(f.bind.apply(f, [self].concat(arguments))); 
    } 
} 

function f(a, b, c, d) { 
    return this + a + b + c + d; 
} 

document.write("f(1, 2, 3, 4) = ", curry(f, 0)(1, 2, 3, 4), "<br>"); 
document.write("f(1, 2, 3)(4) = ", curry(f, 0)(1, 2, 3)(4), "<br>"); 
document.write("f(1)(2, 3, 4) = ", curry(f, 0)(1)(2, 3, 4), "<br>"); 
document.write("f(1)(2)(3)(4) = ", curry(f, 0)(1)(2)(3)(4), "<br>"); 

我無法理解的是:

還有就是通過使用綁定製F的新副本()。已經提供的參數被分配給副本,但變量「self」是什麼?

我試圖「小品」我的意思:

// Second parenthesis (marked with =>): There are three of four 
// expected parameter provided: 
document.write("f(1, 2, 3)(4) = ", curry(f, 0) => (1, 2, 3) <= (4), "<br>"); 

// Makes an array-literal with "self" (== 0) as only element in it. 
// Then adds the parameter already provided to these array by 
// using concat(). => Results in an array [ 0, 1, 2, 3 ]. 
// Then makes a new copy of f with these values bind to it as parameter. 
// These new instance of the function is then passed to the curry-function. 
return curry(f.bind.apply(f, [self].concat(arguments))); 

F的副本,應該有它的四大參數。應該執行併產生「返回0 + 0 + 1 + 2 + 3;」並返回6.

爲什麼不是這種情況?

也許有人可以回答。我會很感激。

+0

第二個「0」來自哪裏?爲什麼只有4個參數中只有3個參數纔會評估('6')? – Bergi

+0

調用咖喱函數並給出0作爲第二個參數(參數「self」)。然後再將自我(=== 0)連同第二個調用的參數(我標記爲=><=)一起使用。在f的主體中,0用於覆蓋this關鍵字的值。所以,因此:this-keyword(== 0)+ 0 + 1 + 2 + 3. 0已被用於覆蓋this關鍵字,它已被添加到給該函數的數組中。所以我認爲這是兩次。 –

+0

無論發生什麼事情,這都是我見過的咖喱最醜陋的實現之一。 – naomik

回答

2

變量「self」是什麼?它用於覆蓋this關鍵字,它已被添加到給該函數的數組中。

不,它不是:

f.bind.apply(f, [self].concat(arguments)) 
≡ f.bind.apply(f, [self].concat([1, 2, 3])) 
≡ f.bind.apply(f, [0, 1, 2, 3]) 
≡ f.bind(0, 1, 2, 3) 

self/0作爲this參數,123結合三個部分地施加參數綁定。這裏沒有重複。其結果是一個函數

function bound_f(x, ...args) 
    return f.call(0, 1, 2, 3, x, ...args); 
} 

被再次咖喱,並且可以與4作爲參數來調用。

+0

A +一如既往的一個很好的解釋,Bergi。 – naomik

+0

@Bergi確實很好的解釋。非常感謝。 –