Unobtrusive Java Script - Namespaces

Namespaces

Unobtrusive JavaScript should add as little as possible to the global object or global namespace of the environment in which it runs. Other scripts may override any variable or function that is created in the global namespace, and this can lead to unexpected failures that are difficult to debug. JavaScript does not have a built-in explicit namespace mechanism, but the desired effects are easy to produce using the language's facilities. Flanagan suggests the use of the developer's own domain name, dotted segments reversed, as a single global name to publish that is very likely to be unique, in the style developed in the Java language.

var org; if (!org) { org = {}; } else if (typeof org != 'object') { throw new Error("org already exists and is not an object."); } if (!org.example) { org.example = {}; } else if (typeof org.example != 'object') { throw new Error("org.example already exists and is not an object."); }

While variables, functions and objects of all kinds can be further defined within such namespace objects, it is usually recommended to use closures within the namespace to further isolate what will become private variables and functions, as well as to export what will be the public interface of each module of functionality. The code above could be followed directly by the following:

org.example.Highlight = function { // Define private data and functions var highlightId = 'x'; function setHighlight(color) { document.getElementById(highlightId).style.color = color; } // Return public pointers to functions or properties // that are to be public. return { goGreen: function { setHighlight('green'); }, goBlue: function { setHighlight('blue'); } } }; //End closure definition and invoke it.

From any other module, these public methods could be invoked in either way as follows

org.example.Highlight.goBlue; var h = org.example.Highlight; h.goGreen;

In this way, each module-writer's code is contained in private or in a unique namespace and cannot interfere with or intrude upon any other code at any time.

Read more about this topic:  Unobtrusive Java Script