[英]Functional Programming: What's the difference between using a closure and using the bind method?
I'm working on a tutorial that explains functional programming. 我正在研究一个解释函数式编程的教程。 He asked me to come with a solution and it worked, but his solution uses the .bind method of the function.
他要求我提供一个解决方案,它可以工作,但是他的解决方案使用函数的.bind方法。
Is there a difference between our solutions other than the syntax? 除语法外,我们的解决方案之间是否还有其他区别?
function mapForEach(arr, fn) {
var newArr = [];
for(var i = 0; i < arr.length; i++){
newArr.push(fn(arr[i]));
}
return newArr;
}
var arr1 = [1,2,3,4,5];
var checkPassedLimitWithBind = function(limiter){
return function (limiter, item) {
return item >= limiter;
}.bind(this, limiter);
};
var checkPassedLimitWithClosure = function(limiter){
return function (item) {
return item >= limiter;
};
};
var notPassed3 = mapForEach(arr1, checkPassedLimitWithBind(3));
var doesNotPass3 = mapForEach(arr1, checkPassedLimitWithClosure(3));
alert(notPassed3);
alert(doesNotPass3);
The examples can be found here as well: https://jsfiddle.net/podbarron/73m86cj3/ 示例也可以在这里找到: https : //jsfiddle.net/podbarron/73m86cj3/
There is absolutely no behavior difference because that function does not use this
. 绝对没有行为差异,因为该函数不使用
this
。
Otherwise it would be different, yes: 否则会有所不同,是的:
var checkPassedLimitWithBind = function(limiter) { return function (limiter, item) { return this == item; }.bind(this, limiter); }; var checkPassedLimitWithClosure = function(limiter) { return function (item) { return this == item; }; }; console.log( checkPassedLimitWithBind.call(123)(123) ); // true console.log( checkPassedLimitWithClosure.call(123)(123) ); // false
The bind
solution is unnecessarily complicated. bind
解决方案不必要地复杂。 There's no need to partially apply the limiter
value there since the function can pretty much access it directly. 由于该函数几乎可以直接访问它,因此无需在此部分应用
limiter
值。
Both will end up working the same way. 两者最终将以相同的方式工作。 However, it can be different if the variable ever gets reassigned (you'd never want to do it with function arguments).
但是,如果重新分配了变量,则可能会有所不同(您永远都不想使用函数参数来执行此操作)。
var checkPassedLimitWithBind = function(limiter){
var fn = function (limiter, item) {
return item >= limiter;
//limiter === argument value for limiter parameter
}.bind(this, limiter);
limiter = 5;
return fn;
};
var checkPassedLimitWithClosure = function(limiter){
var fn = function (item) {
return item >= limiter;
//limiter === 5 all the time
};
limiter = 5;
return fn;
};
Answering the post title: Basically, the closure will have access to whatever value that reference is holding. 回答帖子标题:基本上,闭包将可以访问引用所拥有的任何值。 When you bind the function you'll get that specific value passed down.
当您绑定函数时,您将获得该特定值的传递。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.