TroyGrosfield.com TroyGrosfield.com

Headline

Encapsulation, Namespacing, and Object Oriented Javascript

Author
by Troy Grosfield
Date
September 15th, 2010
Category
Developer
Story

Global functions and/or variables in Javascript can be very bad at times especially when there are many people working on a single project. In order to prevent naming collisions it’s a good idea to namespace your Javascript functions and variables and focus on encapsulation when needed.

Issue

Lets say you have multiple Javascript files:

  1. common.js
  2. utils.js
  • Developer “Bob” puts a function in common.js called getId.
  • Developer “Susie” puts a function in utils.js called getId.
  • Both common.js and utils.js are pulled into the html page at the end of a file.  Each getId function having a different implementation.  Which getId method gets called?

Resolution

Namespace your Javascript when possible!  Namespacing allows you to encapsulate your methods and variables so they stay confined within a certain namespace.

Namespace Code Example

Create an empty hello namespace. It won’t functionally do anything for us. It simply works as the first part of the namespace.

var hello = function(){
    return {};
}

Next, let’s add our first namespace hello.world and give it some private and public functions and variables.

hello.world = function(){
    // private variables to hello.world
    var id, last_name, first_name;  
    
    // private method to hello.world
    function setId(val){
        id = val;
    }

    // public functions
    return {
        init: function(first, last){
            this.setFirstName(first);
            this.setLastName(last);
            setId(Math.floor((Math.random()*9999)+1000));
        },
        setFirstName: function(name){
            first_name = name
        },
        getFirstName: function() {
            return first_name;
        },
        setLastName: function(name){
            last_name = name;
        },
        getLastName: function(){
            return last_name;
        },
        getId: function(){
            return id;
        }
    }
}();

Lets create a second namespace called hello.earth.

hello.earth = function(){
    // private variables to hello.earth
    var id, message;

    // private function to hello.earth
    function setId(val){
        id = val;
    }

    // public functions
    return {
        init: function(msg){
            this.setMessage(msg);
            setId('123456');
        },
        getMessage: function(){
            return message;
	},
        setMessage: function(text){
            message = text;
	},
        getId: function(){
            return id;
        }
    }
}();

Both hello.world and hello.earth contain a private function called setId and private variable called id. However, since each resides in it’s own namespace, neither one knows about the other so no naming collision will occur.

Calling the Namespace

// Initialize hello.world object
hello.world.init("Troy", "Grosfield"); 
document.write(hello.world.getFirstName() + "<br/>");
document.write(hello.world.getLastName() + "<br/>");
document.write(hello.world.getId() + "<br/>");

// Initialize hello.earth object
hello.earth.init("H2O");  
document.write(hello.earth.getId() + "<br/>");
document.write(hello.earth.getMessage() + "<br/>");
document.write(hello.world.getId() + "<br/>");

//hello.setId("21");  <-- private function.  When this call is  
//                        made you see "hello.setId is not a function"
//hello.world.setId("21");  <-- private function. When this 
//                              call is made you see 
//                              "hello.world.setId is not a function"

You'll see if you try and run the code and call the setId function outside of either namespace you get the Javascript error message stating the function doesn't exist. It's private and can only be accessed inside of it's own namespace. Therefore, no naming collision will occur.

Script Output

Troy
Grosfield
5924
123456
H20
5924

You have successfully added namespaces to your Javascript!

Tags
Comments
3 Comments »

3 Comments

Leave a reply

 
  1. Author
    painter 11
    Date
    January 17th, 2011 at 1:33 am
    Comment

    Really love all these stories.. have been reading them daily. Please add more if you have any… Thanks a lot again for this awesome work.

  2. Author
    provides access
    Date
    January 16th, 2011 at 4:42 pm
    Comment

    Good entry. I appreciate you for posting it. Keep up the fine blogging.

  3. Author
    skube
    Date
    October 22nd, 2010 at 2:39 pm
    Comment

    This is the first explanation of encapsulation and namespacing that I understood completely. Bravo! Thank you!