Isolating your code with closures

When writing unobtrusive javascript code one technique often used to isolate code from the rest of the scripts on the page is creating and immediately executing an anonymous function, like this:

function() {
  // Code to isolate may be put in here
  function sayHello() {
    alert("Hello World!");

  window.greet = function() {

// You can use greet here, but not sayHello
greet(); // Alerts "Hello World!"

Here is the twist. Because function greet was explicitly assigned to the window object (which represents the global scope), we may call it even after the anonymous function has finished. It is available in the global scope. But we can’t reach function sayHello. It effectively has become private. The cool thing is that function greet can still reach sayHello so it can now make use of private helper functions without those functions being exposed to the outside world. They are isolated.

The reason this works is that the anonymous function creates a new scope, so any variables and functions declared in it are isolated from the other code on the page. It encloses all functions and variables inside it and they remain available even after the function terminates. This principle is called a closure and it forms the foundation of Packages JS, my package management project.

You can read more about closures (including some excellent and very technical analysis of how and why it works) on the JavascriptWeblog article
Understanding JavaScript Closures.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s