Available for Hire!

ProgFu

programming tips & tricks

Mar 7

Private JavaScript variables with the Module Pattern

In the previous article, we’ve talked about closures which are the building stone for anything even remotely complex in JavaScript. This time, we’ll take a look at private variables.

JavaScript itself doesn’t have the concept of a private or public variable, everything is public. But there’s a way around this. Let’s take a look at our previous example

var counter = (function() {
  var count = 0;
  return function() {
    return ++count;
  }
})();

The variable count here can be thought of as private, because it can’t be referenced from outside of the counter. But this can go much further than just having a private variable for one function, we can do this with objects too.

var cat = (function() {
  var name = "bob";

  return {
    getName: function() {
      return name;
    },
    miaow: function() {
      console.log("miaow");
    }
  }
})();

console.log("the cat's name is", cat.getName());

There’s nothing really complicated about this, we’re just returning an object at the end, and since all its functions act as closures, they can access our private variables.

But it doesn’t end here, we can also define a private method

var cat = (function() {
  var name = "bob";

  var secret = function() {
    console.log(name, "doesn't have any secrets");
  };

  return {
    getName: function() {
      return name;
    },
    miaow: function() {
      // we can call te private method anywhere we want
      secret();
      console.log("miaow");
    }
  }
})();

console.log("the cat's name is", cat.getName());
// but this will cause an error,
// because the method isn't visible from the outside
cat.secret();

The important thing to note here is that there aren’t really any limits on nesting function definitions in JavaScript. Even though it’s generally not a good practice to have too many levels of nesting, sometimes it can be helpful.

In the next article, we’ll take a look at this, how and when it changes and what are some common patterns.


  1. klaatu reblogged this from progfu
  2. progfu posted this
Page 1 of 1