How to structure your javascript. Part 2


Hi and welcome to the second edition of this javascript tutorial =)

In this tutorial I'm going to show Object Oriented capabilities (emulation) in javascript.
As you may know, javascript is an interpreted language and was not conceived to be object oriented for many reasons, actually nobody though it would be used as it is right now.

You can probably be wondering, why would I need this in js? well, I you like to become a javascript ninja, this is were you need to start.

In all of the next examples we're going to be using JSON (javascript object notation). If you have no clue what this is, take a look at this tutorial.

Let's begin =)

One of the neat features of the OO paradigm is to create "objects" which have methods and properties that "encapsulate" this characteristics within the object. In our first example we will create a car.


//car object first approach
var car = {
speed : 0
,accelerate : function(){
this.speed++;
}
,tachometer : function(){
alert(this.speed);
}
}

//Accelerate the car
for(var i = 0; i<=100; i++){
car.accelerate();
}

//How fast am I going?
car.tachometer();


In this example we created a car object which has properties (speed) and methods (accelerate, tachometer), using this approach we can only have one car, the one we just created and that's it, it is like a super variable (Singleton) with methods and properties and that's not too object oriented :S.
I use this approach as my application entry point were I initialize all of my components.


The second approach is as follows:

//car object second approach
var car = function(){
//Private Variables
var speed = 0;

return{
//Prublic variables
doors : 4
//Public functions with access to private variables
,accelerate : function(){
speed++;
}
,tachometer : function(){
alert(speed);
}
}
};

//create car instances
var bmw = new car();
var audi = new car();

//Accelerate the car
for(var i = 0; i<=100; i++){
bmw.accelerate();
}
//Notice that we haven't move our audi from the garage =P
bmw.tachometer(); // alerts 99
audi.tachometer(); // alerts 0


This example has more OO properties that the first one, here we have public and private variables and also methods plus with this approach we can create instances of the object and use it several times.

Important Note: Notice how some variables are declared using var and others not, when we use "var" inside a function the variable is "trapped" inside the scope of that function and any other that might be inside of it. I you declare variables without the "var" you're creating global variables attached to the "window" namespace.

I know i raised the bar a little bit in this post, so if I confuse any of you, let me know and I will modify the post.

Thanx for reading =)

0 Comments:

Post a Comment