Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

accessing variables in javascript closures

var add = (function () {
    var counter = 0;
    return function () { 
        var reset = function() {
            counter = 0;
        }
        return counter += 1;
    }
})();

This is a self-invoking function that creates a "private" variable. How would I create a function reset that will reset the counter to 0? I've tried declaring the function inside the closure, but when I call it using add.reset(), it tells me this method is undefined.

like image 730
bluejay5 Avatar asked Jun 08 '26 07:06

bluejay5


2 Answers

You should return the reset function as a method of the object returned by the IIFE. That object needs to be the add function, so put the reset method on it. Just do it like you would in a global context, but inside a closure and return the add function, e.g.:

var add = (function(){
  var counter = 0;

  function add(n) {
    counter += n || 0;
    return counter;
  }

  add.reset = function(){
    counter = 0;
    return counter;
  }

  return add;
}())

console.log(add(1)) // 1
console.log(add(4)) // 5
console.log(add.reset()); // 0

However, it would make more sense (to me) to have a counter object that has add and reset methods.

like image 159
RobG Avatar answered Jun 10 '26 17:06

RobG


I would recommend that instead of trying to put the function inside your closure, you put your variable outside your closure, like this:

var counter = 0;

var add = function() {
    return counter += 1;
};

var reset = function() {
    counter = 0;
};

That way the variable has proper scope for what you are trying to accomplish with it.

like image 32
Maximillian Laumeister Avatar answered Jun 10 '26 17:06

Maximillian Laumeister