📜 ⬆️ ⬇️

Javascript namespace 2

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



The code looks like this:
')
 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 I’m talking about namespaces, I’ll mention at the same time the technique of imitating 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 techniques will seem useful to someone.

Source: https://habr.com/ru/post/26763/


All Articles