Last active
August 29, 2015 14:07
-
-
Save greggnakamura/1e4ce72cbe5c5b402fb7 to your computer and use it in GitHub Desktop.
Javascript: Namespacing with the Module Pattern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
"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."