Skip to content

Instantly share code, notes, and snippets.

@Lobstrosity
Created August 10, 2011 00:19
Show Gist options
  • Save Lobstrosity/1135611 to your computer and use it in GitHub Desktop.
Save Lobstrosity/1135611 to your computer and use it in GitHub Desktop.
JavaScript Module Pattern
var message = 'Hello!';
(function() {
var message = 'Hi!';
alert(message);
})();
var message = 'Hello!';
(function() {
alert(message);
var message = 'Hi!';
})();
var message = 'Hello!';
(function () {
var message;
alert(message);
message = 'Hi!';
})();
var createPerson = function(name) {
var _name = name;
return {
getName: function() {
return _name;
}
};
};
var joe = createPerson('Joe');
alert(joe.getName());
(function(module, undefined) {
// Anything declared at this level is only accessible within this
// function. Efectively, they will be the module's private variables.
var _answer = 42;
// The module's public interface is then defined by declaring variables on
// the module variable that was passed in.
module.getAnswer = function(question) {
return _answer;
};
})(window.module = window.module || {});
module.getAnswer('Huh?');
(function(m) {
m.doStuff = function() {
// TODO: Stuff
};
})(window.deeply.nested.module);
window.deeply.nested.module.doStuff();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment