Created
August 10, 2011 00:19
JavaScript Module Pattern
This file contains hidden or 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
var message = 'Hello!'; | |
(function() { | |
var message = 'Hi!'; | |
alert(message); | |
})(); |
This file contains hidden or 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
var message = 'Hello!'; | |
(function() { | |
alert(message); | |
var message = 'Hi!'; | |
})(); |
This file contains hidden or 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
var message = 'Hello!'; | |
(function () { | |
var message; | |
alert(message); | |
message = 'Hi!'; | |
})(); |
This file contains hidden or 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
var createPerson = function(name) { | |
var _name = name; | |
return { | |
getName: function() { | |
return _name; | |
} | |
}; | |
}; | |
var joe = createPerson('Joe'); | |
alert(joe.getName()); |
This file contains hidden or 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
(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?'); |
This file contains hidden or 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
(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