User Defined Objects in JavaScript

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:

Source Code

<html>
<head>
  <title>User Defined Objects prepared by Ashish Bhatnagar</title>
  <style>
    body {
      font-family: Arial, sans-serif;
    }
    table {
      border-collapse: collapse;
      width: 100%;
    }
    th, td {
      border: 1px solid black;
      padding: 8px;
      text-align: left;
    }
    th {
      background-color: #f2f2f2;
    }
  </style>
</head>
<body>
  <h2>Please enter the search criteria and click the "List Records" Button</h2>
  <h3>Leave blank if you don't want to give a search criteria</h3>
  <form name="empform">
    <table>
      <tr>
        <td>Name</td>
        <td><input type="text" name="ename"></td>
      </tr>
      <tr>
        <td>Dept. No.</td>
        <td><input type="text" name="deptno"></td>
      </tr>
      <tr>
        <td>Phone</td>
        <td><input type="text" name="tel"></td>
      </tr>
      <tr>
        <td colspan="2" align="center"><input type="button" value="List Records" onClick="display()"></td>
      </tr>
    </table>
  </form>

  <script>
    function empObject(name, deptno, phone) {
      this.name = name;
      this.deptno = deptno;
      this.phone = phone;
    }

    var emp = [
      new empObject("Ashish", "120", "8993929292"),
      new empObject("Rahul", "130", "2993998291"),
      new empObject("Krishan", "160", "7483339291"),
      new empObject("Sunil", "180", "7448429382"),
      new empObject("Mohan", "133", "6373828498"),
      new empObject("Raghav", "134", "9394847392"),
      new empObject("Ritesh", "122", "9383748383"),
      new empObject("Sameer", "110", "839472828"),
      new empObject("Sonu", "139", "83927382922"),
      new empObject("Sumit", "185", "93038483832")
    ];

    function display() {
      var s = "";
      s += "<table>";
      s += "<tr><th>Name</th><th>Dept. No.</th><th>Phone</th></tr>";
      var nm = document.empform.ename.value.toUpperCase();
      var dno = document.empform.deptno.value;
      var ph = document.empform.tel.value;
      var ct = 0;
      for (var i = 0; i < emp.length; i++) {
        if ((nm === "" || emp[i].name.toUpperCase().indexOf(nm) !== -1) &&
            (dno === "" || emp[i].deptno === dno) &&
            (ph === "" || emp[i].phone === ph)) {
          s += "<tr><td>" + emp[i].name + "</td>";
          s += "<td>" + emp[i].deptno + "</td>";
          s += "<td>" + emp[i].phone + "</td></tr>";
          ct++;
        }
      }
      if (ct === 0) {
        s += "<tr><td colspan='3' align='center'>No Records Found</td></tr>";
      }
      s += "</table>";
      var newWin = open("", "empDetails", "width=400,height=300");
      newWin.document.write(s);
      newWin.focus();
    }
  </script>
</body>
</html>

This script code defines a simple web page for displaying a list of employee records based on search criteria such as name, department number, and phone number.

Output

User defined object in JavaScript output

Summary

JavaScript supports the creation of user-defined objects. Constructor is the building block of all database objects. A Constructor is a special function that allows us to create custom objects and their instances. Constructor defines the properties and methods of an object.


Similar Articles