Question: Functional Programming: What's the difference between using a closure and using the bind method?

Question

Functional Programming: What's the difference between using a closure and using the bind method?

Answers 2
Added at 2017-01-02 02:01
Tags
Question

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.

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/

Answers
nr: #1 dodano: 2017-01-02 02:01

There is absolutely no behavior difference because that function does not use 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

nr: #2 dodano: 2017-01-02 04:01

The bind solution is unnecessarily complicated. There's no need to partially apply the limiter value there since the function can pretty much access it directly.

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.

Source Show
◀ Wstecz