Bulk Emailing

  • Subscribe to our RSS feed.
  • Twitter
  • StumbleUpon
  • Reddit
  • Facebook
  • Digg

Wednesday, 6 April 2011

Overriding In JavaScript

Posted on 23:41 by Unknown
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
Email ThisBlogThis!Share to XShare to Facebook
Posted in | No comments
Newer Post Older Post Home

0 comments:

Post a Comment

Subscribe to: Post Comments (Atom)

Popular Posts

  • CityWeather
    Update: Release 1.1 has been uploaded. It will now provide weekly forecast of your selected cities. Download   CityWeather is an Android...

Blog Archive

  • ►  2013 (6)
    • ►  September (2)
    • ►  May (1)
    • ►  April (1)
    • ►  February (1)
    • ►  January (1)
  • ►  2012 (4)
    • ►  July (2)
    • ►  March (1)
    • ►  January (1)
  • ▼  2011 (11)
    • ►  November (1)
    • ►  October (2)
    • ►  August (1)
    • ►  June (1)
    • ▼  April (2)
      • JSON to Java Bean conversion for Android
      • Overriding In JavaScript
    • ►  March (3)
    • ►  January (1)
  • ►  2010 (27)
    • ►  December (2)
    • ►  November (3)
    • ►  September (2)
    • ►  August (4)
    • ►  July (4)
    • ►  June (7)
    • ►  May (5)
Powered by Blogger.

About Me

Unknown
View my complete profile