Javascript Code Namespace 2

    After reading a note about using namespaces in Javascript code, I wanted to share the approach that I use. It was not invented by me, of course, but maybe someone does not know about it. This approach differs from those proposed in that article in that, in addition to functions and data visible from the outside, it is also possible to define data and functions local to the namespace and invisible from the outside.



    The code is as follows:

    App = function ()
    {
       // public data
       var FooMember = 3;
       // public function
       function foo ()
       {
         // use private data
         alert (_FooMember);
         // call private function
          _foo ();
       }
       // private data
       var _FooMember = 4;
       // private function
       function _foo ()
       {
       }
       return {
           FooMember: FooMember,
           foo: foo
       }
    } ();
    


    Using this code is obvious:
       alert (App.FooMember);
       App.foo ();
    


    Since we are talking about namespaces, I will mention at the same time the technique of simulating enumeration in Javascript. Instead of writing code like:
       var STORY_NEW = 1;
       var STORY_UPDATE = 2;
       var STORY_DELETE = 3;
       ..........
       switch (tag) 
       {
          case STORY_NEW: ...; break;
          case STORY_UPDATE: ...; break;
          case STORY_DELETE: ...; break;
          ...
       }
    


    You can write the following:

       var StoryAction = {
          New: 1,
          Update: 2,
          Delete: 3,
          ....
       };
       ...
       switch (tag) 
       {
          case StoryAction.New: ...; break;
          case StoryAction.Update: ...; break;
          case StoryAction.Delete: ...; break;
          ...
       }
    


    I hope that these two tricks seem useful to someone.

    Also popular now: