Monday, January 12, 2009

JavaScript : More than alerts , decoration and validation

Most of the developers, especially the web developers think that JavaScript is embedded with web pages to perform Alerts, Decorations and Validation. Is it true?
Here I will make sure to prove it false. Let’s start with OOPs with Java Script.


Java Script supports OOPs. Many of the developer think that JS (JavaScript) is derived from JAVA which is not true. JAVA is a language which is compiled while JS is an interpreted language.

How to create a class using JS ?

function Student(name,age){

How to create object from this class ?
var student=new Student(“Krishan”,31);
Providing getter and setter to class
function Student (name,age){

return this.sName;


Note: don’t get confused with prototype . You will get it shortly.

Using getter and setter

var student=new Student(“Temp”,20);

JS a Dynamic Language:

Java Script is very dynamic language and do like anything. Following examples explains dynamic nature of JS.

Assigning method calls to events:

function callMeOnLoad(){
alert(“Page has been loaded”);

Above code will call callMeOnLoad method once webpage is loaded. Same way you can assign function call to other events.

Assigning methods while constructing the class:

function MethodAssignment= function(){

function initialize(){”xxx”;

Var obj=new MethodAssignment();

Note that”xxx” in initialize function, 'this reference' is pointing to obj in above code as initialize method is assigned to callMe method and will be invoked when ever obj.callMe() is invoked. Is it useful for providing same function in more than once class, with same behavior?


Prototyping is a very strong feature from JavaScript and provides extensibility. Suppose you have a already written java script class and your want to extent it's functionality without making any change in the original class, I show you how to do that

Let’s say there is a class Student provided by some third party,

function Student (name){

return this.s_name;

This class only provides name to a student, if you also want to have age in this class then you have to extent this class using prototype property of class. Please go through the code below.

Student.protype.getAge=function (){
return s_age;

Above code will add setAge and getAge method to Student class and all the objects created from Student class will have these methods.

prototype property can be used for inheritance as well.

function BaseStudent (school){

Now say

Student.prototype= BaseStudent;

Code above will set BaseStudent as super class for Student class.

I am just starting a habit of writing blog, so have fun .....

Koi bekadar Kahiye, Nagina nahi mujhe |
Tere Haaton mai kaid hokar, jeena nahi mujhe ||