public
Created

JavaScript Module Pattern

  • Download Gist
1.scope.js
JavaScript
1 2 3 4 5 6 7
var message = 'Hello!';
 
(function() {
var message = 'Hi!';
 
alert(message);
})();
2.scope.js
JavaScript
1 2 3 4 5 6 7
var message = 'Hello!';
 
(function() {
alert(message);
 
var message = 'Hi!';
})();
3.scope.js
JavaScript
1 2 3 4 5 6 7 8 9
var message = 'Hello!';
 
(function () {
var message;
 
alert(message);
 
message = 'Hi!';
})();
4.closure.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13
var createPerson = function(name) {
var _name = name;
 
return {
getName: function() {
return _name;
}
};
};
 
var joe = createPerson('Joe');
 
alert(joe.getName());
5.modulePattern.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
(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?');
6.modulePattern.js
JavaScript
1 2 3 4 5 6 7
(function(m) {
m.doStuff = function() {
// TODO: Stuff
};
})(window.deeply.nested.module);
 
window.deeply.nested.module.doStuff();

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.