Skip to content

Instantly share code, notes, and snippets.

@jacksoncharles
Last active December 22, 2015 05:29
Show Gist options
  • Save jacksoncharles/6424691 to your computer and use it in GitHub Desktop.
Save jacksoncharles/6424691 to your computer and use it in GitHub Desktop.
Courtesy Steven Robinson, simple example with inline docs. The outer function is the closure, and even after it returns, everything within it is still available in memory.
<script type="text/javascript">
// define a var to be used as an app namespace
var APP = (function () {
// define an object which will be returned, single 'var' pattern
var app = {},
// define some private 'functions' and vars if necessary
priv1 = function () {
console.log('priv1');
},
priv2 = function () {
console.log('priv2');
},
priv3 = function () {
console.log('priv3');
};
// assign any functions you want to become public to the app var
app.method1 = priv3;
// return the app var
return app;
}());// this is a self invoking immediate function, when the page loads (script runs), APP will get the return value immediately (Object app)
// outside of the self invoking function, APP === Object app, returned from the outer function
APP.method1(); // logs 'priv3'
APP.priv1(); // logs 'Uncaught TypeError', function is private (but could be called from within priv3 and still accessible in APP)
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment