PaulSelles/entropy.js — pull request #1 by mwbrooks (2013-04-08 04:21:14+00:00)
Title: Encapsulate in a self-executing anonymous function.

### Overview

When writing JavaScript for a web browser, you need to be careful with global objects.

### What is a Global Object

- Global objects are attached to `window`.
- Any user can viewed and edit the object (with a web inspector).
- Any other script can access, edit, or replace any global object.

### Creating Global Objects

- Any object declared in the open is considered global.
- Any object declared without a `var` is considered global.

### Common Code Practice

You can both prevent global objects and write clean code by using a self-executing anonymous function.

(function(args) {
// code
})(params);

An anonymous function is a function without a name: `function() {};`. In contrast to `var fn = function() {};` and `function fn() {}`, which has the name `fn`.

A self-executing function is one that executes when it is declared. You can accomplish this by wrapping a function in parenthesis, which captures the function (instead of capturing it with a name):

(function() {
});

// similar to
var fn = function() {
};

and then calling it the function as a normal:

(function() {
})();

// similar to
var fn = function() {};
fn();

Finally, you can pass dependencies into the function as parameters:

(function(window, sha1) {
// code
})(window, sha1);

// similar to
var fn = function(window, sha1) {
};
fn(window, sha1);

Lastly, you will notice that anything declared inside the function cannot be accessed globally. In order to expose an object globally, you will want to pass `window` as a dependency and manually attached objects.

(function(window, sha1) {
function MyModule() {
}

// expose globally
window.MyModule = MyModule;
})(window, sha1);