Skip navigation

You can modify classes after they have been defined and objects after they have been instantiated.

The above statement may seems strange to classic OOPs programmers. But JavaScript is prototype based language.

/* Class Person. */
function Person(name, age) {
   this.name = name;
   this.age = age;
}
Person.prototype = {
   getName: function() {
   return this.name;
 },
 getAge: function() {
   return this.age;
  }
}
/* Instantiate the class. */
var raja = new Person('Raja', 36);
var vinoj = new Person('Vinoj', 26);

/* Modify the class. */
Person.prototype.getGreeting = function() {
   return this.getName();
};
/* Modify a specific instance. */
raja.displayGreeting = function() {
   alert(this.getGreeting());
}

/* Now raja alone have method displayGreetings */

In this example, the getGreetingmethod is added to the class after the two instances are created, but these two instances still get the method, due to the way the prototype object works. raja also gets the displayGreetingmethod, but no other instance does.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: