javascript prototype

Understanding javascript prototype

Every object in javascript has got a prototype method which basically adds new methods to the base object which then can be called on instance objects.

Comparing with other languages , constructor functions are classes and the properties of the prototype (i.e. of the object referenced by the constructor function’s prototype property) as shared members, ie members which are the same for each instance. In class-based systems, methods are implemented the same way for each instance, so methods are normally added to the prototype, whereas an object’s fields are instance-specific and therefore added to the object itself during construction.

A simple example

Type this in Chrome Devtools console :

function Animal() {} // This is a first class functional object
Animal.prototype.speak = function() { console.log('OK'); } //Add a prototype function
var cat = new Animal(); //Creates a new Animal
cat.speak(); // Will call that function and print OK

In the above example we first defined the constructor function and then added speak function to it.
We then initialized cat as an Animal and called the that function on it.

Another Example

//Define a functional object to hold Animal
var Animal = function(name) {
    this.name = name;
};

//A new getter for that name
Animal.prototype.getName = function() {
    return this.name;
};

//Create a new object of type Animal
var cat = new Animal("Kitty");

//alert(cat.getName()); will use the getter

//This is where we add the speak function to Animal
Animal.prototype.speak = function() {
    alert('Hello, my name is ' + this.getName());
};

//Call the new method on cat
cat.speak();

When you will run the above code in devtools console , you will get an alert saying My name is Kitty.
In the above example , we created the instance object then added a method to the base , and then called the new method on the instance object.
This is how Inheritance works in javascript.

Sources :

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

http://ejohn.org/apps/learn/#65

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>