A prototype is a property present in every object that allows to add methods and properties.
In Javascript there is no real distinction between class and object.
Every object is declared as a function.
var myObj = function() {}
Or
function myFunc() {}
You can then add new methods using the prototype property:
myObj.prototype.doSomething = function() {document.write("Writing something");}
You can also add properties and methods without prototype:
myObj.doSomething() {document.write("Dummy method");}
But in this case the property or object exist only for the current instance and not the others:
var myObj = function() {} myObj.doSomething() {document.write("Writing something");} var otherObj = new myObj(); otherObj.doSomething(); // You get an error here!
By using prototype, the properties and the methods are automatically propagated to all the objects, as demonstrated in this code:
var obj1 = function() {}; obj1.prototype.saySomething = function() { document.write("Saying something"); }; var obj2 = function() {}; obj2.prototype = new obj1(); new obj2().saySomething();
This is an other example:
var obj1 = function() {}; var obj2 = new obj1(); obj1.prototype.saySomething = function() { document.write("Saying something"); }; obj2.saySomething();
However a prototype is examined only when a new object is created, so this code generate error:
var obj1 = function() {}; obj1.prototype.saySomething = function() { document.write("Saying something"); }; new obj1.saySomething(); // This is fine obj1.saySomething(); //This generate error
A chain of prototypes is formed with each creation, where a prototype constitute a template only for the derivated objects and not the current one.
Copyright © 2013 Welcome to the website of Davis Fiore. All Rights Reserved.