3

Can someone explain me how is the _.before function implemented as i dont really understand why the internal times variable keeps track of every function call. Shouldn't it be in local scope and reset every time like normal functions ?

Code for _.before function :

  // Returns a function that will only be executed up to (but not including) the Nth call.
  _.before = function(times, func) {
    var memo;
    return function() {
      if (--times > 0) {
        memo = func.apply(this, arguments);
      }
      if (times <= 1) func = null;
      return memo;
    };
  };

Thank you.

123onetwothree
  • 636
  • 1
  • 8
  • 17
  • You need this http://stackoverflow.com/questions/111102/how-do-javascript-closures-work – Maxx Aug 09 '16 at 13:39

2 Answers2

0

The key is func.apply(this, arguments) makes the anonymous function recursive. The scope of times is outside the inner anonymous function. When the closer is called --times is executed, with the scope of times being the before function.

Matt S
  • 14,976
  • 6
  • 57
  • 76
0

Because of a concept named closures, the returned function in your example "remembers" the environment in which it was created. In that case, it remembers both times and func arguments, even though it's returned.

Read more about closures: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures