A JavaScript Module Pattern
Written by on June 13th, 2007 in Ajax News.
Eric Miraglia, of Yahoo!, has documented his explanation of what Douglas Crockford calls the JavaScript Module pattern.
Eric discusses the steps:
- Create a namespace object: If you’re using YUI, you can use the YAHOO.namespace() method
- Assign the return value of an anonymous function to your namespace object
- Add “private” methods and variables in the anonymous function prior to the return statement
- Do something useful with the pattern
JAVASCRIPT:
-
-
YAHOO.myProject.myModule = function () {
-
-
//"private" variables:
-
var myPrivateVar = “I can be accessed only from within YAHOO.myProject.myModule.”
-
-
//"private" method:
-
var myPrivateMethod = function () {
-
YAHOO.log(”I can be accessed only from within YAHOO.myProject.myModule”);
-
}
-
-
return {
-
myPublicProperty: “I’m accessible as YAHOO.myProject.myModule.myPublicProperty.”
-
myPublicMethod: function () {
-
YAHOO.log(”I’m accessible as YAHOO.myProject.myModule.myPublicMethod.”);
-
-
//Within myProject, I can access "private" vars and methods:
-
YAHOO.log(myPrivateVar);
-
YAHOO.log(myPrivateMethod());
-
-
//The native scope of myPublicMethod is myProject; we can
-
//access public members using "this":
-
YAHOO.log(this.myPublicProperty);
-
}
-
};
-
-
}(); // the parens here cause the anonymous function to execute and return
-
Note that this technique is very generic, and you can do the same thing with other frameworks, or without any frameworks!
Source: Ajaxian
Original Article: http://ajaxian.com/archives/a-javascript-module-pattern