Day 86, how to mimic closure

Question: how to mimic closure without using closure?

Answer: use bind.

The following code will work, inspired by the “Functional JavaScript”.

/* closure */
var multiply = function (byN) {
  return function(arg) {
    console.log('always multiply by ' + byN + ' because of closure. Result is: ', arg * byN);
  };

};

var finalFunc = multiply(5);
finalFunc(10);

In the code above, byN belongs to the scope of multiply(). In other words, byN is used by the anonymous function, and byN is outside the scope of that anonymous function. Hence, it is using closure.

/* mimicking using bind */
var _ = require('underscore');

var multiply = function (byN) {
  return function(arg) {
    var captures = {'byN': byN};

    var bindFn = _.bind(function(){
      console.log('always multiply by ' + this['byN'] + ' because of closure. Result is: ', arg * this['byN']);
    }, captures);
    bindFn();
  };

};

var finalFunc = multiply(5);
finalFunc(10);

In the code above, byN belongs to the anonymous function. Hence, we are not using anything outside of the scope of the anonymous function.

Advertisements
Standard