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:

  1.  
  2. YAHOO.myProject.myModule = function () {
  3.  
  4.         //"private" variables:
  5.         var myPrivateVar = “I can be accessed only from within YAHOO.myProject.myModule.”
  6.  
  7.         //"private" method:
  8.         var myPrivateMethod = function () {
  9.                 YAHOO.log(”I can be accessed only from within YAHOO.myProject.myModule”);
  10.         }
  11.  
  12.         return  {
  13.                 myPublicProperty: “I’m accessible as YAHOO.myProject.myModule.myPublicProperty.”
  14.                 myPublicMethod: function () {
  15.                         YAHOO.log(”I’m accessible as YAHOO.myProject.myModule.myPublicMethod.”);
  16.  
  17.                         //Within myProject, I can access "private" vars and methods:
  18.                         YAHOO.log(myPrivateVar);
  19.                         YAHOO.log(myPrivateMethod());
  20.  
  21.                         //The native scope of myPublicMethod is myProject; we can
  22.                         //access public members using "this":
  23.                         YAHOO.log(this.myPublicProperty);
  24.                 }
  25.         };
  26.  
  27. }(); // the parens here cause the anonymous function to execute and return
  28.  

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

Leave a Reply

You must be logged in to post a comment.



Site Navigation