Creating Objects

By: aathishankaran Printer Friendly Format    

Most of the time you will be referencing objects, which are built-in to the DOM.

However, you may want to create your own objects for storing data within a JavaScript program. There are several ways to create a new object, but we'll look at two: creating a direct instance of an object and creating an object prototype. 

direct instance of an object 

Despite the awkward sound name, a "direct instance of an object" simply means creating a new single object, such as myPetDog: 

myPetDog=new Object () ;"Barney";



Assigning a method to your new object is also simple. Assume that you already have coded a function named woof0, which causes a barking sound to play: 


Prototype of an object 

Sometimes, you'll want to create a "template" or prototype of an object. This does not create an actual instance of the object, but defines the structure of the object. In the future, then, you can quickly stamp out a particular instance of the object. Suppose that instead of myPetDog, you created a prototype object named petDog. This object could then be a template for a particular pet dog object. First, create a function which defines the petDog structure: 

function petDog(name, breed, year)


this. name = name;

.this. breed = breed;

this. year = year;


Now that the petDog prototype has been set, you can quickly create single instances of a new object based on the petDog structure: 

myPetDog=new petDog(“barney","beagle",1981);

yourPetDog=new petDog(“max","terrier",1990); 




<Title>User Defined Objects</Title>



function Print ()


document.write (“Employee Number: “+this.Eno);

document.write ("<br>") ;

document.write ("Employee Name: "+this. Ename) ;

document.write ("<br>");

document.write ("Employee Salary: “+this. Salary) ;


function Hra ()


document.write ("<br>") ;

document.write("HRA: "+(this.Salary*SO/lOO»;




function Employee(Eno,Ename,Salary)









</ Script>


<Body bgcolor=#c0c0c0>


var emp0l=new Employee(l00,"aathishankaran”,90000);

emp0l. Print ( ) ;

emp0l. Hra( ) ;

</ Script>




Employee Number : 100

Employee Name : aathishankaran

Employee Salary : 90000

HRA : 45000

Most Viewed Articles (in Java )

Latest Articles (in Java)

Comment on this tutorial