|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Announcements
Chapters
Services
Feature Zones
|
IntroductionJavaScript can not only do client side validation, but can also solve complex problems. Here, I am going to explain how to use classes in JavaScript. OOPs to POPsMost programmers use hundreds of functions in a single web page or in a separate js file, and it is too difficult to make changes on them because they are function oriented. Think about object oriented programming. OOP makes things simple and easy as we can split our objectives into objects. We are not lucky! JavaScript doesn't have support for OOP but it supports prototype oriented programming (POPs). Creating the Employee ObjectConsider the typical <script>
/*
Employee
--------
Fields:
Id
Name
EmployeeCollection
-------------------
Fields:
indexer
count
Functions:
Add
Delete
Display
*/
//This Function is used to create the collection object.
//Copy this function to create your own collection objects.
function CreateCollection(ClassName)
{
var obj=new Array();
eval("var t=new "+ClassName+"()");
for(_item in t)
{
eval("obj."+_item+"=t."+_item);
}
return obj;
}
function EmployeeCollection()
{
this.Container="";
this.Add=function(obj)
{
this.push(obj);
}
this.Display=function()
{
str="<Table border=1 width=200 ><tr><td>" +
"<b>Name</b></td><td><b>" +
"Age</b></td><tr>";
for(i=0;i<this.length;i++)
str+="<Tr><Td>"+this[i].Name+
"</Td><Td>"+this[i].Age+
"</Td></Tr>";
str+="</Table>";
this.Container.innerHTML=str;
}
}
function Employee(Name,Age)
{
this.Name=Name;
this.Age=Age;
}
//Using the EmployeeCollection and Employee Obejcts
empCollection=new CreateCollection("EmployeeCollection");
empCollection.Add(new Employee("Jax",26));
empCollection.Add(new Employee("Shionk",45));
empCollection.Add(new Employee("Maya",25));
empCollection.Container=document.getElementById("grid");
alert(empCollection[0].Name);
empCollection.Display();
</script>
How it works" ConclusionAt last, we implemented some of the OOP concepts in JavaScript. I'm now trying to implement inheritance in JavaScript.
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||