Skip to content

Instantly share code, notes, and snippets.

@greggnakamura
Last active August 29, 2015 14:07
Show Gist options
  • Save greggnakamura/1e4ce72cbe5c5b402fb7 to your computer and use it in GitHub Desktop.
Save greggnakamura/1e4ce72cbe5c5b402fb7 to your computer and use it in GitHub Desktop.
Javascript: Namespacing with the Module Pattern
// http://javascriptweblog.wordpress.com/2010/12/07/namespacing-in-javascript/
/* Namespacing - The Module Pattern */
var myApp = (function () {
var id = 0;
return {
next: function () {
return id++;
},
reset: function () {
id = 0;
}
};
})();
console.log(myApp.next(), myApp.next(), myApp.reset(), myApp.next());
// 0 1 undefined 0
@greggnakamura
Copy link
Author

"The logic is shielded from the global scope by a function wrapper (usually self-invoking) which returns an object representing the module’s public interface. By immediately invoking the function and assigning the result to a namespace variable, we lock up the module’s API in the namespace. Additionally any variables not included in the return value will remain forever private, visible only to the public functions that reference them."

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment