in Projects, Programming, Technology

Simple Javascript Namespaces

Javascript doesn’t have to the capacity to define namespaces. When you’ve got snippets of javascript spread all over there is the possiblity for name collisions. The commonly practiced work around is to create a graph of class objects and properties so that you can have a hierarchical naming structure. I’ve copied what YUI does, and made my own implementation. I thought I would share what I’ve learned.


1. MyCo.js provides a helper function to create a namespace that all our javascript should use:

MyCo.namespace(“MyCo.Product.App”); // or whatever you want your namespace to be

This will create the namespace if it doesn’t already exist.


2. Create a “class” definition:


MyCo.Product.App.MyControl = function() { // constructor};

YUI also makes frequent use of hashtable syntax here:

MyCo.Product.App.MyControl = { name: “Jack B. Nimble”, ‘goto’: ‘Jail’, grade: ‘A’, level: 3};


3. Assign functions to that class object:

MyCo.Product.App.MyControl.DoSomething = function() { // do something }


4. Reference your function using your class:

MyCo.Product.App.MyControl.DoSomething();

Write a Comment

Comment