Thursday, April 7, 2011

Overriding In JavaScript

Here I'll explain the usage of a powerful keyword/programming structure of JavaScript, "prototype". It is one of the member variable of Function object and Function object is kind of Supper class for any function that you write in JavaScript. Every function in Javascript is of type Function object.

"prototype" provides really a powerful and simple way of extending JavaScript Object and Override their existing functions. Prototype provides additional look up chain for variable and method definition search.

So, lets take an example, say there is a JavaScript object Person having First and Last name and we want to override  the default toString() method of prototype property. toString() displays string representation of any object.
               function Person(fname, lname){
                       this.fname = fname;
                       this.lname = lname;
               }
               Person.prototype.toString = function(){
return "Person Name: "+ fname +" "+ lname;
               };
 Usage-
var person = new Person("Alan", "Miers");
alert(person);

Now, lets define the Person object with 2 methods displayName() and reverseName().
                function Person(fname, lname){
this.fname = fname;
this.lname = lname;
};
// Add methods
Person.prototype.fullName = function(){
return this.fname + " "+ this.lname;
};
Person.prototype.reverseName = function(){
return this.lname + " "+ this.fname;
};


A good source of JavaScript guide- Mozilla Development Network

No comments:

Post a Comment