Skip to content
  • home
  • portfolio
  • web design journal
  • blog
    • adventure
    • san diego
    • projects
    • website design
    • code notes
Blog Web Dev Namespacing in Javascript

Namespacing in Javascript

By Forrest Smith - Drempd.com

So the other night I was working on some fancy script. It didn't work. After a bit of investigation, it turns out that one of the function names was already being used by a different function. Bummer. Of course this is why people use namespacing, to avoid problems such as this. So, here's how to write a sample bit of code to utilize namespacing in javascript:

 var myApp = (function(){
     var numericval = 10;

     return{
          moveLeft: function(){
               alert('left:'+numericval);
          },
          moveRight: function(){
               alert('right');
          }
     };
})();

$(document).ready(function(){
     $('.left').click(myApp.moveLeft);
});

Or to call it from other javascript code:

      myApp.moveLeft();

I don't really care for nesting all of my functions within the namespace declaration, so you can also do something like the following, outside of the namespace:

var myApp = (function(){
//some code in here
return{} //Make sure to include this line
})();

myApp.testFunction = function(){
//some code here
}

Posted on April 1, 2014December 26, 2023 in Web Dev

drempd | san diego, ca


home contact

adventures san diego projects stream website design

portfolio resume san diego web design freelance web designer

custom web design responsive web design website maintenance