Saturday, 20 April 2013

Namespace Javascript

Use object literals in javascript to namespace functions, and creates simple modules. To avoid function name collisions in javascript.
//Printer object
var Printer = {  
  //we can store variable in Printer object scope
  message: 'Hello World', 

  //function in Printer object
  printToConsole : function(){ 
    //'this' refers to the Printer object
    //and '.message' to field above
    console.log(this.message)
  },
  
  //function in Printer object
  printToScreen  : function(){
    window.alert(this.message) 
  }
  
  //function in Printer object
  printEverywhere : function(){
    this.printToScreen();
  }
}
Now we can call these functions like so:
Printer.printToConsole(); // will print Hello world to the console

Printer.printToScreen(); //will print Hello world in alert box

Printer.printToConsole(); // will print Hello world to the console

Printer.printEverywhere(); //will print Hello world in alert box, then console
We can now define another object literal with the same function names and not cause collisions.

No comments:

Post a Comment