How to structure your javascript. Part 1

Hi everyone, today i'll talk about javascript coding practices and how to structure your code to avoid variable collisions when making big js applications.

Every time a page is loaded, the client (browser) creates a variable/namespace called "window" which is like a little native framework provided on any page by the browser.
This namespace contains basic information about the client like view port width and height, the document variable, and many others. The naming of each variable can change from browser to browser and that's the primarily reason why javascript frameworks are created.

When we declare a js variable it is "stored" within the window namespace:

//run this code in Firebug console
foo = 1;
alert(window.foo);
alert(foo);

//Alerts 1 two times


As we can see, everything we declare this way is going to be saved withing the window namespace. Right now everything works perfect because we are using only one foo var, but what happen if we start creating a javascript widget which has a lot of functions and variables, we will "pollute" this namespace and ran out of names sooner or later.

If we want to keep our global namespace (window) clean, we can use an "anonymous" function to create a "closure" and encapsulate our variables inside. If you dont know what a javascript closure is, what are you waiting? take a look at this link.

Example:


//delete the foo variable from last example
delete foo;

(function(){
var foo = 1;

})();

//undefined uh?
alert(foo);



After running this snippet, we can take a look to the window variable in firebug and see that there's no "foo" variable listed inside, which means we can only use our foo variable inside that closure. Anonymous functions are very useful, it is also important to remember that a function in javascript is also a variable type along with strings, ints, arrays and objects:


var foo = function(){
alert("Function as a variable =)");
}

alert(typeof(foo));

//use it like this
foo();


This examples are very basic but i've found that no so many web developers know about 'em.

In part 2 we will continue with JSON classes and how they help us to emulate Object Oriented capabilities in javascript =) its going to be interesting and hopefully by the end of this series we will be able to start writing our own javascript framework =)

Thanx for reading!



0 Comments:

Post a Comment