Sunday, April 21, 2013

Javascript Prototype Object



Prototype is a builtin js property that is part of JS objects. It was introduced in JS version 1.1.
Prototype object can be added only to Function,String, Image, Number, Date and Array.
We can use prototype on the base class not on the objects derived from it.
The prototype object help you quickly add a custom method or member to an object that is
reflected on ALL instances of it.
Prototype object can only be used to add PUBLIC member and methods. It cannot add private
members or methods.
If the prototype object is used to override the the previously set property it will not override the
properties of already created objects. It will only affect the objects that have been created after
the prototype change.

Using prototype on custom objects:


var func = function(){};
func.prototype.foo = "bar"; //adds the property foo
alert(func.foo); //alerts undefined
func2 = new func();
alert(func2.foo); //alerts bar
func2.prototype.foo2 = 'ddd'; //Error : func2.prototype is undefined
Using prototype on builtin JS objects:

String.prototype.foo = "bar";
Image.prototype.foo = "bar";
Number.prototype.foo = "bar";
Array.prototype.foo = "bar";
You cannot use prototype on derived objects:
var str = new String();
str.prototype.foo = 'bar'; //Error : str.prototype is undefined




With Regards,
Animesh Nanda,
Sr. Software Engineer | Photon Infotech
Bengaluru | Karnataka | INDIA.

No comments:

Post a Comment