[英]how does javascript's closure work if we want to preserve a value in currying
[英]JavaScript's bind() with currying. How does these code work?
这些代码两天前发布在CodeReview上:
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>");
我不明白的是:
使用bind()创建了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。
为什么不这样呢?
也许有人可以回答。 我会很感激。
变量“ self”是什么? 它用于覆盖this-keyword,并且已添加到该函数提供的数组中。
不,这不对:
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
论点, 1
, 2
和3
结合三个部分地施加参数。 这里没有重复的内容。 结果是一个函数
function bound_f(x, ...args)
return f.call(0, 1, 2, 3, x, ...args);
}
然后再次进行咖喱处理,并可以使用4
作为参数来调用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.