Thursday, November 26, 2009

Working with Object Oriented Javascript

There are many situations we use javascript on web application. Most of us use it for client side validation or to load some dynamic content on client side. There are many things we can achieve using javascript. Here I thought of explaining some basics of object oriented approach to work with javascript.

First thing you shoud keep in mind is that object oriented in javascript is not like any other progamming languages like C#, Java, C++ where we are referring to instances of classes or structs. There is nothing like creating class on javascript. We can assume that its a collection of name value pairs or dictionary with string keys. Simple way to express that as we create a function and assign that to a variable. Here is how the sample Javascript class file will look like



<script>

function Myclass(){
this.myPublicvar = '';
var method1 = function()
{
if(arguments.length > 0){

alert("parameter length" + arguments.length);
}
else
{
alert("inside the method " + this.myPublicvar);
}
}

this.mypublicMethod = method1;
}


function alertme(){
var myObj = new Myclass();
myObj.myPublicvar = 'Sample';
myObj.mypublicMethod();
}


function testoverloading()
{
var myObj = new Myclass();
myObj.mypublicMethod(1);
myObj.mypublicMethod(1,'Test parameter');

}
<script>


<input onclick="alertme()" value="Click here" type="button">
<input onclick="testoverloading()" value="Try Overloading" type="button">




In above case, we have a function created as Myclass which will act as a class. There is a method defined inside Myclass method1. The method1 is assigned to a public variable myPublicMethod.

When you create a object of Myclass, you can invoke the method by using myObj.mypublicMethod(); As you can see in the above example it has one of the public variable defined myPublicvar. Now you must have understood the use of "this" keyword inside the function Myclass.



We can also achieve function overloading. In above scenario, we have one more button “Try Overloading” which will invoke a method testoverloading(). This will show how the overloading works. One of the feature of javascript that makes it very flexible that,we can pass any number of parameters and we can get them as parameter array. You can find the same in above example. The same public method mypublicMethod is invoked with different parameter. The alert will show the number of parameter passed.


When you are working with complicated logic on client side this will help us a lot. Hope this piece of information will give some basic idea on object oriented approach on javascript programming.

You can get details on http://msdn.microsoft.com/en-us/magazine/cc163419.aspx

No comments:

Post a Comment