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
}
-
Adventure
-
The Built Environment
-
Locations
-
Web Dev