Javascript Prototype

Lot of confusions we do have always on this concept. Myself facing the same issue until i found this..

The prototype property is initially an empty object, and can have members added to it – as you would any other object.

var myObject = function(name){ = name;
    return this;
console.log(typeof myObject.prototype); // object
myObject.prototype.getName = function(){

In the snippet above, we’ve created a function, but if we call myObject(), it will simply return the window object, because it was defined within the global scope. this will therefore return the global object, as it has not yet been instantiated (more on this later).

console.log(myObject() === window); // true

anyways i found a simple example in stackoverflow too..

here it is..

In a language implementing classical inheritance like Java, C# or C++ you start by creating a class–a blueprint for your objects–and then you can create new objects from that class or you can extend the class, defining a new class that augments the original class.

In JavaScript you first create an object (there is no concept of class), then you can augment your own object or create new objects from it. It’s not difficult, but a little foreign and hard to metabolize for somebody used to the classical way.


//Define a functional object to hold persons in JavaScript
var Person = function(name) { = name;

//Add dynamically to the already defined object a new getter
Person.prototype.getName = function() {

//Create a new object of type Person
var john = new Person("John");

//Try the getter

//If now I modify person, also John gets the updates
Person.prototype.sayMyName = function() {
  alert('Hello, my name is ' + this.getName());

//Call the new method on john


Leave a Reply

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

You are commenting using your 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