Tag Archives : Javascript

Javascript prototype in action

Post on December 18th,2011 by

In this article I am going to show you a simple javascript program which will add instance function to the constructor function using the constructor’s prototype. Click below button to run the sample code:

In order to run the whole code we will need to create an object with the constructor function as follow:

var sayHi = function(hi) {
this.hi = hi;
};

The object above will receive a string and then assign it to a variable for future use. Now we create an instance function like below:

sayHi.prototype.hello = function(){
  alert(this.hi);
};

Finally create an instance of the above object and call the instance function.

var sayHello = new sayHi("Hello World!");
sayHello.hello();

The code above will show an alert box with the text ‘Hello World!’ later.