Skip to content

Instantly share code, notes, and snippets.

@tbranyen
Last active December 30, 2015 02:39
Show Gist options
  • Save tbranyen/7764590 to your computer and use it in GitHub Desktop.
Save tbranyen/7764590 to your computer and use it in GitHub Desktop.
// Super contrived example. This is an IIFE. It executes immediately so that the
// privateProperty is in the nested scope and so that the Module property is
// actually assigned the function (named inner) instead. If we didn't make it an
// immediately-invoked-function-expression (IIFE) then Module would be a function
// that once called would be the new (inner) function.
//
// I'm returning an object inside inner() that has the scope outside of that function.
// That's what makes this a true closure. It's that I'm able to reference variables
// from functions outside out of the one I'm currently running. Basically in this
// example. Module == inner (they are the same thing). So when we call module, we're
// actually calling inner, but it still has access to privateProperty, even though we
// may be in separate files. This is cool, since we can have "private" properties or
// do other crazy shit. It also means we have to be careful in large applications,
// because we may store too much and cause memory problems when unrelated data is held
// onto.
var Module = (function() {
var privateProperty = {};
// This is a closure to lock in the privateProperty, from the enclosing scope
// (important that it's outside the following function.)
return function innner() {
var publicProperty = "expose me";
// privateProperty is the same in here for anyone who uses module.
// privateProperty.i = privateProperty.i ? privateProperty.i++ : 1;
return {
publicProperty: publicProperty
};
};
})();
// Now you can see:
Module().publicProperty === "expose me";
Module().privateProperty === undefined;
var privateProperty = {};
var publicProperty = "expose me";
exports.publicProperty = publicProperty;
// Now you can see
require("./above-file").publicProperty === "expose me";
require("./above-file").privateProperty === "undefined";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment