Tuesday, October 6, 2009

JavaScript Object Creation

What i observed is, we can create custom Objects in JavaScript in 3 ways:
  1. singleton
  2. singleton compact (used in json)
  3. template (class).

Now i will show examples for each:

1. Singleton - once created, no further independent instances are possible from it.

var personObj=new Object();



personObj.eat= function(val){ txt.value+=val; };

2. Singleton Compact - similar to above, but useful in JSON format.

var newObj={name:'rozy',age:5,eat:function(){txt.value+='eat';}};

3. Template / Class - It enables multiple instances can be created.

function person(firstname,lastname,age,eyecolor){


this.age=age;this.eyecolor=eyecolor;this.newlastname=newlastname; }

function newlastname(new_lastname){ this.lastname=new_lastname; }

No comments:

Post a Comment