Wednesday, October 18, 2006

# posted by shashank mishra @ 11:46 AM
 

Creating a Class in JavaScript

Have you ever used the keyword CLASS with JavaScript?

I think NO, as there is no keyword CLASS in JavaScript. But you may want to create some class that has functions and constructors. It is easy to do so.
*Just Put this code inside script tags.
1. function Printer(company, type)
2. {
a.) this.company=company;
b.) this.type=type;
3. }
4. printerLaser = new Printer('HP','Laser Jet');
5.printerDotMatrix = new Printer('EPSON','Dot Matrix');
6.with (printerLaser) document.write('Printer 1: Company Name >> '+ company
+' and type '+type+'');
7.with (printerDotMatrix) document.write('Printer 2: Company Name >> '+ company +
' and type '+type+'');

Lets review the code line by line:
Line 1: We declared a function Printer that will set the properties of newly creating object.
Line 2 (a, b): This will refer to the current scope i.e. current Object.
Line 4,5: Creation of new Object.
Line 6, 7: We will get the reference to the Objects using with(object)
Isn’t it quite simple?
So, what a Class is supposed to do? Here is the answer:
1. Any object of the Class can use the method defined in the Class without rewriting its own and how we will make it possible? The one word answer is:
PROTOTYPE [“Prototype means that if a class is inherited from another class, then it can borrow all of its methods, so we don't need to redefine them.”]
Now you will be thinking how we are going to do this! Why bother, just have a look on the code:
*Put this code inside script tags.
function Printer(name, company,type)
{
this.name = name;
this.company = company;
this.type = type;
}
function view()
{
with (this) document.write(name+': Company>> '+company+' and type is, '+type+'');
}

Printer.prototype.view = view;
printerLaser = new Printer('printerLaser','HP','Laser Jet');
printerDotMatrix = new Printer('printerDotMatrix', 'EPSON','Dot Matrix');
printerLaser.view();
printerDotMatrix.view();
Now what else we added here is:
Printer.prototype.view = view;
that is making the view function a prototype for all the Printer types i.e. Printer Objects
and printerLaser.view();
the Printer types (objects) are now able to access the view function with there reference.

What this code does. It will create a function view() only once and all the Printer Objects will have access to it.