Create namespace in JavaScript

  Peter        2012-05-10 04:57:17       5,789        0    

A namespace (sometimes also called a name scope) is an abstract container or environment created to hold a logical grouping of unique identifiers or symbols (i.e., names). An identifier defined in a namespace is associated only with that namespace. The same identifier can be independently defined in multiple namespaces. That is, the meaning associated with an identifier defined in one namespace may or may not have the same meaning as the same identifier defined in another namespace. Languages that support namespaces specify the rules that determine to which namespace an identifier (not its definition) belongs[1].

JavaScript is an OOP language, it can also have namespace. In JavaScript, it's very easy for us to make mistakes when we define variables, for example, when we are using some 3rd party frameworks, we may define some variables in our own script which have the same name as those in the 3rd party frameworks. In order to solve these conflicts, we may create our own namespaces and define our classes and variables in the namespace so that they will not affect the normal work of those frameworks.

Here are some examples to create namespaces in JavaScript.
(function( skillet, $, undefined ) {
   
//Private Property
   
var isHot = true;

   
//Public Property
    skillet
.ingredient = "Bacon Strips";

   
//Public Method
    skillet
.fry = function() {
       
var oliveOil;

        addItem
( "\t\n Butter \n\t" );
        addItem
( oliveOil );
        console
.log( "Frying " + skillet.ingredient );
   
};

   
//Private Method
   
function addItem( item ) {
       
if ( item !== undefined ) {
            console
.log( "Adding " + $.trim(item) );
       
}
   
}    
}( window.skillet = window.skillet || {}, jQuery ));

So if you want to access one of the public members you would just go skillet.fry() or skillet.ingredients

What's really cool is that you can now extend the namespace using the exact same syntax.

//Adding New Functionality to the Skillet
(function( skillet, $, undefined ) {
   
//Private Property
   
var amountOfGrease = "1 Cup";

   
//Public Method
    skillet
.toString = function() {
        console
.log( skillet.quantity + " " +
                     skillet
.ingredient + " & " +
                     amountOfGrease
+ " of Grease" );
        console
.log( isHot ? "Hot" : "Cold" );
   
};    
}( window.skillet = window.skillet || {}, jQuery ));

Pros

  • Gives you the ability to have public and private properties and methods
  • The code inside doesn’t use the Object Literal notation
  • Keeps undefined’s value as undefined in case someone overrode the value
  • Allows you to use $ inside your code without worrying about clashing with other libraries
  • Allows your library to grow across files using the “window.namespace = window.namespace || {}” technique
  • A common pattern that you will see in many libraries, widgets, and plugins

Cons

  • Slightly more complicated pattern, but not overly difficult to understand[2]

Another relative simple example is [3]

function registerNS(ns)
{
 var nsParts = ns.split(".");
 var root = window;

 for(var i=0; i<nsParts.length; i++)
 {
  if(typeof root[nsParts[i]] == "undefined")
   root[nsParts[i]] = new Object();

  root = root[nsParts[i]];
 }
}


registerNS("Michael.Ajax.Utilities");

Michael.Ajax.Utilities.RegisterCallback = function(e, callback)
{

 // ...
}

Michael.Ajax.WebService = function(wsdl, async)
{
 this.wsdl = wsdl;
 this.async = async;

 // ...
}

// sample usage

var ws = new Michael.Ajax.WebService(http://.../service1.asmx?WSDL, true);
ws.onready = function(res)
{
 alert(res.value);
}
ws.ServerAdd(21, 2);

We can follow these two patterns when we need to create namespaces in our JavaScript. The advantage of using namespace is to make our code reusable and avoid conflict among different frameworks since there are many JavaScript libraries around us and we will frequently use them. This also reduces the potential bug and maintain cost.

References 

[1].http://en.wikipedia.org/wiki/Namespace_%28computer_science%29

[2].http://enterprisejquery.com/2010/10/how-good-c-habits-can-encourage-bad-javascript-habits-part-1/

[3]. http://weblogs.asp.net/mschwarz/archive/2005/08/26/423699.aspx

JAVASCRIPT  EXAMPLE  NAMESPACE 

       

  RELATED


  0 COMMENT


No comment for this article.



  RANDOM FUN

Cascading