Wednesday, July 25, 2012

JavaScript OOP Basics (Tutorial)

Today i want to explain the JavaScript OOP basics (The basics of Object Oriented JavaScript).

JavaScript OOP, but looks functional language, but in real environment and point of view, it is pure OOP language.
Why JavaScript is an OOP Language?
Let's take a look at usual function
function testFunc(){
   alert('The Test');
}

Seems like normal function isn't it?
Nope, it is method.
In JavaScript all functions and variables is wired up to context, in above example assume we use it without any class context, but function still method of object.
Which object is the context if we defined the function outside any context?
We defined the function in scope of "window", the basic JavaScript object in page.
So the function is accessible also through:
var it_is_variable = 'Test It';

function testFunc(){
   alert('The Test');
}

// call function
window.testFunc();
// alerts "The Test"

// same with variables
alert(window.it_is_variable);
// alerts "Test It"

Function's variables also accessible in an OOP manner, such as:
function jstest(){
   test_var = 'test';
   alert(self.test_var);
}


How to create a JavaScript Object?
var obj = {};

Here we created a blank javascript object by using curly braces.

Adding functionality to an object in JavaScript
Lets create a few properties and methods.
var obj = {}; // the previous code

obj.propertyA = 'test_property'; // adding property

// adding method
obj.getProperty = function(){
   alert(this.propertyA);
}

obj.getProperty(); // alerts the propertyA of class obj


Let's create real environment object.
var car = {
   // properties as object
   dimentions : {
      len : 462,
      width : 190,
      height : 110,
      weight : 1250
   },
   // properties
   tank : 40,
   color : 'red',
   maxSpeed : 220,
   horsePowers : 125,
   _handBrake : true,
   _power : false,
   // Methods
   init : function(){
       if(!this._power)
           this.startEngine();
       
       return this._power;
   },
   startEngine : function(){
       if(true === this._power)
           return true;
       if(true === this._handBrake)
           this.handBreakSwitch();
       this.checkFuel();
       this.powerSwitch();
   },
   refill : function(){
       this.tank = 40;
   },
   handBreakSwitch : function(){
       this._handBreak = (this._handBreak === false ? true : false);
   },
   checkFuel : function(){
       if(this.tank < 5)
           this.refill();
       return true;
   },
   checkEngine : function(){
      if(true === this._power)
         return true;
      else
         this.startEngine();
   },
   powerSwitch : function(){
       this._power = (this._power === false ? true : false);
   },
   paint : function(color){
       this.color = color;
   },
   drive : function(distance,velocity){
       this.checkEngine();
       return (parseInt(distance) / parseInt( this.calcSpeed(velocity) ) ).toFixed(3) + 'sec';
   },
   calcSpeed : function(speed){
       return (speed*1000)/(60*60);
   }
};

// Lets initialize the car
car.init();

// Unfortunately the dimentions of the car and horsepowers are not used in current
// example as far as starting speed (velocity), i won't spend much time on example ;-)

//using car.drive(1230,90) in alert
alert('Time spent to pass distance is ' + car.drive(1230,90));
// Alerts "Time spent to pass distance is 49.200s" 
// so we traveled 1230 meters with speed 90km/h in 49.2sec.

car.paint('blue');
alert('Car painted with ' + car.color + ' color.');


Overriding in effect
Typical overriding is as simple as
var car = {
   init : function(){
      alert('test');
   }
};
// alerts 'test'
car.init();

car.init = function(){
   alert('override in effect');
};

// Alerts "Override in effect"
car.init();​


Javascript class constructor
Class constructor in javascript defines as a function it will also enable you to access to prototype, but... prototypes,inheritance and closures in next articles.
function car(){
   this.init = function(){
      alert('test');
   }
}

// initializes class with constructor
var car = new car;
// alerts 'test'
car.init();


Have fun playing JavaScript's funny oop:)
Sincerely,
Ruskevych Valentin


Other JavaScript Tutorials and How To

How To Verify Function exists in a JavaScript Class
How to get styles of the elements properly in Javascript (Solving the bugs)
TableSorter Installation a Detailed Tutorial.

2 comments:

Unknown said...

this is a really good javascript tutorial, thanks for sharing

Unknown said...

I appreciate your rating.
If you have any question, mystery left hidden, please let me know and i will make it clearer in this tutorial.
Thank you again.