Search code examples
javascriptmethodsnamespacesyuijavascript-namespaces

How can I create an empty namespace object without overwriting another object with the same name?


I have been studying as much as I can about the Module Pattern suggested by the Yahoo YUI Blog.

I've noticed that the YUI offers the ability to create a new empty namespace object without overwriting an existing one of the same name like so:

YAHOO.namespace("myProject");

Which can then be called and used with YAHOO.myProject

(Reminder: if YAHOO.myProject already exists it is not overwritten)

How can I achieve a similar effect using plain javascript, and without using the YUI?

Please explain with as much detail as possible.

The full YUI blog article where this is done can be found here.

As I am learning and srengthening my javascript knowledge and skills, I am trying to create my own personal javascript library (even if I never need to use it)


Solution

  • In your example, it could work like this:

    if (!YAHOO.myProject) {
        YAHOO.myProject = {};
    }
    YAHOO.myProject.whatever = true;
    

    or using your own parent module name:

    var myModule = myModule || {};  // make sure parent is defined without overwriting
    if (!myModule.myProject) {
        myModule.myProject = {};
    }
    myModule.myProject.whatever = true;
    

    Or define your own namespace function:

    function myNamespace(item) {
        if (!myModule[item]) {
            myModule[item] = {};
        }
    }
    
    myNamespace("myProject");
    myNamespace.myProject.whatever = true;