user2167582
user2167582

Reputation: 6378

how does javascript's closure work if we want to preserve a value in currying

I have written the code

// Handlers
function successHandlerFactory (savedFlag) {

  return function (res, savedFlag){
    if (res.data && res.status == 200) {
      ngcoupon_offerManager.addOffers(res.data.offers, -1, savedFlag);
      console.log('offers response', res, 'savedFlag', savedFlag);
    } else {
      console.error('something is wrong to get offers', res);
    }
  }
};

var offerSuccessHandler = function() {
    return successHandlerFactory();
}();
var savedofferSuccessHandler = function () {
  return successHandlerFactory(true);
}();

but apparently its giving out savedFlag undefined every executinon I make.

How come this does not work

Upvotes: 0

Views: 58

Answers (1)

Patrik Oldsberg
Patrik Oldsberg

Reputation: 1550

The issue is in this part of the code:

function successHandlerFactory (savedFlag) {
  return function (res, savedFlag){
    ...

You're re-declaring savedFlag in the inner function, which ends up being the variable that is captured in the success handler. Try simply removing the second parameter of the returned function.

Upvotes: 5

Related Questions