Introduction
JavaScript provides a number of pre-defined objects like Array, String, Image, Date, etc., which are very useful in web development. However, our use of objects in JavaScript is not limited to these predefined objects. JavaScript also allows you to create objects of your own. An Object is similar to a record as it can contain various fields or properties that are shared by all instances of the object. In addition, objects can be constructed to include certain methods or functions that enable you to control the behavior of the object. Representing programming constructs as objects allows you to create sophisticated solutions with a minimum of coding. Also, it allows us to create efficient schemes for form evaluations or create client side databases.
Creating a user-defined object
The first step in creating a user-defined object is to create a constructor, which is the building block of all user-defined objects. A Constructor is a special function that allows you to create custom objects and their instances. It defines the properties and methods of your object and also creates a template from which instances can be generated.
Let us create an object for maintaining an employee phone list. The following constructor can be used for the same.
function empObject(name, deptno, phone)
{
this.name=name
this.deptno=deptno
this.phoneno=phone
this.display=display
}
The above constructor creates an object names empObject and defines three properties (name, deptno, and phone) and one method (display()) for the empObject.
To use this object, we have to create a new instance of the object.
Creating an instance of a user-defined object
To create instances and populate the properties of each new instance with actual data, variables must be declared. For example, to add an employee to your object model, we must use the following statement:
ashish=new empObject(“Ashish”,”120”,”8993929292”)
In order to create a client-side database of employee records. We will add the employee objects to an array.
emp=new Array();
emp[0]=new empObject(“Ashish”,”120”,” 8993929292”)
emp[1]=new empObject(“Rahul”,”130”,” 9993998291”)
emp[2]=new empObject(“Krishan”,”160”,” 7483339291”)
emp[3]=new empObject(“Sunil”,”180”,” 74848429382”)
emp[4]=new empObject(“Mohan”,”133”,” 6373828498”)
emp[5]=new empObject(“Raghav”,”134”,”9394847392”)
emp[6]=new empObject(“Ritesh”,”122”,” 9383748383”)
emp[7]=new empObject(“Sameer”,”110”,” 83947284828”)
emp[8]=new empObject(“Sonu”,”139”,” 83927382922”)
emp[9]=new empObject(“Sumit”,”185”,” 93038483832”)
Defining Object Methods
In order to retrieve the information stored in an instance of an object, you must define methods that allow you to view the data in the instance.
The following listing demonstrates the creation and usage of objects in JavaScript:


Join the conversation! Your thoughts help the community grow.