JavaScript Objects


JavaScript is an object-oriented language and everything is an object here.

A JavaScript object is an entity having state (properties) as well as behaviour (methods).

An object is like a variable which can contain multiple values. It is a container for named values.

Example:

    var student = {name:”Abhi”, rollNo:1027, course:”CS”};

The values are written as name:value pairs.

Note: JavaScript objects can’t be compared, Comparing 2 javascript objects will always returns false.


Creating Objects

We can create objects in 3 different ways:

a) By object literal
b) By creating instance of Object directly (using new operator)
c) By using an object constructor (using new operator)


1. Creating object by object literal

Syntax:

    objectName = {property1:value1, property2:value2,...,property:valueN};


Example:

    var student = {name:”Abhi”, rollNo:1027, course:”CS”};



2. Creating object by creating an instance of object

Syntax:

    var objectName = new Object();
    objectName.property1 = value1;
    objectName.property2 = value2;


Example:

    var student = new Object();
    student.name = “Abhi”;
    student.rollNo = 1027;    


3. Creating object by using an object constructor

Syntax:

    function objFunction (property1, property2, property3)
    {
        this.property1 = property1;
        this.property2 = property2;
        this.property3 = property3;
    }
    var objectName = new objFunction (value1, value2, value3);        


Example:

    function studentDetails (name, rollNo, course)
    {
        this.name = name;
        this.rollNo = rollNo;
        this.course = course;
    }
    var student = new studentDetails (“Abhi”, 1027, “CS”);        



Defining a method in JavaScript object

We can also define a method in a JavaScript object.

Example:

    function studentDetails (name, rollNo, course)
    {
        this.name = name;
        this.rollNo = rollNo;
        this.course = course;
        this.changeRollNo = changeRollNo;
        function changeRollNo (newRollNo)
        {
            this.rollNo = newRollNo;
        }
    }
    var student = new studentDetails (“Abhi”, 1027, “CS”);
    document.write (student.name + “ “ + student.rollNo + “ “ + student.course);
    student.newRollNo(1030);
    document.write (student.name + “ “ + student.rollNo + “ “ + student.course);


Output:

    Abhi 1027 CS
    Abhi 1030 CS