Introduction Object-Oriented JavaScript Perfect Class Simulation

In, one of my previous post I gave introduction to Object Oriented Programming in JavaScript. In that, I couldn't explain about Simulating Class concept. Today, I will explain complete class simulation concept in javascript. For those who don't know what is this Class simulation, Class simulation means Implementing one of the Object Oriented Programming paradigm Class concept even thought JavaScript don't support natively. The belwo example codes can be use in our day to day projects. Let's Start.
Introduction Object-Oriented JavaScript Perfect Class Simulation

Prepare

We need a html page to run and see how our JavaScript code works. So let's create a simple html page as below.

<html>  
<head>  
<title>Introduction Object-Oriented JavaScript Perfect Class Simulation</title>  
</head>  
<body>  
<script type="text/javascript">  
//Write your code here..... 
</script>  
</body>  
</html> 

1) Basic Class

I have already explained how the basic class simulation can be done in my previous post JavaScript Object Oriented Programming(OOP) Tutorial.

//only for example 
function Class(){ 

} 
//to create object using class. 
var object=new Class(); 

This is good. But I'm changing the code as.

//only for example 
var Class=function(){ 

} 
//to create object using class. 
var object=new Class(); 

There is no difference between above two. But with second method it will be very useful when we dealing with large scale JavaScript apps with namespaces. We can create all your namespaces and Classes names separately and use them when we need. So that we can maintain app Architecture easily.

2)Constructor

This concept also we discussed in my previous OOJS post. But here i'm gonna add default values options.

var Class=function(prop1,prop2){  
this.prop1=prop1 || default_prop1;  
this.prop2=prop2 || defualt_prop2;  
}; 
var obj=new Class("val1","val2"); 

Here, We created a Class. It will allows to take two argument when we create object using new operator. Inside our Class we check if the user passed any argument or not. If any argument is not passed we will apply default value for the arguments. Let's see an example. Let's say we have a Web-Page and we want to give customization options to user. To choose colors for font and page background. If no colors has passed we want to put font color white and background as black. Then our JavaScript code will be.

var Page=function(font,bg){  
this.font=font || '#fff';  
this.bg=font || '#000';  
//dom code to apply changes 
document.body.style.backgroundColor=this.bg;  
document.body.style.color=this.font;  
}; 
var pageObj=new Page('#262626','#f2f2f2'); 

Isn't it so cool.

3) Constructor Another way

The above Constructor is good but I always like wrap the code in functions. I really wish if we can have Constructor just like other OO Programming languages have. For example in PHP we have constructor as _construct function. So that we can wrap all Class initialization code in it. Now let's simulate the same concept in JavaScript. I'm gonna call my constructor function as init function.

var Class=function(prop1,prop2){  
this._init=function(){  
this.prop1=prop1 || default_prop1;  
this.prop2=prop2 || defualt_prop2;  
}; 
this.func1=function(){  
//Your first function here.... 
}; 
this.func2=function(){  
//function2 code here.... 
}; 
//calling init 
this._init();  
}; 
var obj=new Class("val1","val2"); 

In here, We have three functions inside the class. Two dummy functions, Which I added to show how it look like if we have more functions inside the Class. One init function. At the end of the class code we have called the init function. So when you create an object the _init function will be called automatically and all code inside of it will get executed. Isn't it great?

4) Destructor

Destructor will be used to delete the current object from memory. But if you ask me is it really useful in JavaScript, I would say no. Because when ever we reload our page all objects will be deleted my themselves. Also JavaScript designed in such way that it will maintain garbage collection my themselves. If we are not using any object it will not be maintained in memory. Anyway, for learning purpose we will create a Destructor simulation in JavaScript as below. We gonna call our Destructor function as _die.
In JavaScript we can't delete the object completely but we can break the relation between the objects and the properties attached to that object. The Destructor code will be...

var Class=function(prop1,prop2){  
//Constructor 
this._init=function(){  
this.prop1=prop1 || default_prop1;  
this.prop2=prop2 || defualt_prop2;  
}; 
this.func1=function(){  
//Your first function here.... 
}; 
this.func2=function(){  
//function 2 code here.... 
}; 
//Destructor 
this._die=function(){  
alert("Deleteing current object");  
for(var prop in this)  
delete this[prop];  
} 
console.log(this);  
}; 
//Calling init 
this._init();  
}; 
var obj=new Class("value1","value2"); 

Here, I extended the same code we used for Constuctor. I added a new function called _die and inside  we wrote our Desctructor code. In Descructor code we wrote a simple JavaScript's For...in loop to go through all objects in side current object and using JavaScript's delete operator we break the relation between all objects under current object. I know it's little difficult to understand. Below I'm attaching console.log images for understand. Now, Open your console(press F12) for the index.html page and run the following code.

obj  
obj._die();  
obj 

Here we simply displaying what is happening object before and after executing the die() function. Before calling die function it will display all properties inside the Class. After calling die, It will return empty class. See screen shot below.
Introduction Object-Oriented JavaScript Perfect Class Simulation-techumber.com

5) Access Specifiers

Access Specifiers(private,public in java,php programming language) are great way to preventing accessing the properties of the Class out the side the Class. First I will show you simplest way to simulate the private public access specifiers in JavaScript. Later we will see a example to understand.

var Class=function(){  
//private variables and functions 
var prop1="some val1";  
var func1=function(){  
//Some code for private function 
}; 
return{  
//all public varibles and functions goes here... 
prop1:"Some value public";  
func1:function(){  
//we can write operation on private properties of class here.. 
}; 
} 
}; 
var obj=new Class(); 

This is the simplest way to simulate private public access specifier in JavaScript. Now let's see an example for this. For example let's say we have Users class. The user have property date of birth(dob). We Don't want to display the dob. But we want to display the age of the user based on dob. We can do that as...

var Person=function(){  
//Date of birth of a person 
var dob=new Date(1990,06,08);  
return{  
//To get age 
getAge:function(){  
return new Date().getYear() - dob.getYear();  
} 
} 
}; 
var aravi=new Person(); 

Now, Open your console and run the code as below. In above image we can only access the public properties not private.
Introduction Object-Oriented JavaScript Perfect Class Simulation-techumber.com

Conclusion:

I feel JavaScript has enough features to do follow Object Oriented programming model. We only need to understand the existing features and use them properly to get more from it. I will try to come up with more concepts on JavaScript. Cheers....

Get posts by email

Like what you're reading? Get these posts delivered to your inbox.