Thursday, October 8, 2009

JavaScript Prototype Object

Before proceeding any further, you should know how to create custom Objects in javascript. If u don't know, read this post.
Prototype Object allows us to add new member to already created/existing Object.
prototype object can be used on any object type:
  • js built-in objects - String, Image etc.
  • custom Objects ( template type).

Now here we will discuss applying prototypes on custom objects:

prototype can be used only on template type objects. which means, objects which allows instance creation by 'new' keyword.

function person(firstname,lastname,age){this.firstname=firstname;this.lastname=lastname;this.age=age; }
var obj=new person("rozy","rojz",24);


function Obj(){};
Obj.prototype = new Array();
Obj.prototype.fn = function(){alert('new method fn of Obj');};
var o = new Obj(); // o is a instance of Obj
o.push(one); alert(o.length);

Prototypes can't be appled on singleton types, since, any new member can be added to it any time directly.
ex: var personObj=new Object();

for further reading/reference: click here.

No comments:

Post a Comment