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.

01
02
03
04
05
06
07
08
09
10
var myObject = function(name){
    this.name = name;
    return this;
};
console.log(typeof myObject.prototype); // object
myObject.prototype.getName = function(){
    return this.name;
};

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).

1
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.

Example:

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

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

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

//Try the getter
alert(john.getName());

//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
john.sayMyName();

Source: http://stackoverflow.com/questions/572897/how-does-javascript-prototype-work

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