Creating JavaScript Objects

In my previous article I explained what a JavaScript Object is. Now let us move further to the creation of objects.

We can create objects in the following two ways:

  1. Object Literals
  2. Object Constructor

Object Literals

The most common and easiest way to create objects is with the object literal described here:

// This is an empty object initialized using the object literal notation

var employee = {};

// This is an object, again using object literal

var employee = {

id:20984

name: "Roger",

department: "IT",

getMessage: function () {

console.log("New Message");

}

} 

Object Constructor

The second most common way to create objects is with an Object constructor. A constructor is a function used for initializing new objects and you use the new keyword to call the constructor.

var employee = new Object();

    employee.id = 20984;

    employee.name = "Roger"; employee.department = "IT";

    employee.getDetails = function () {

    console.log("This is a " + this.name + "working in " + this.department);

} 

Objects can contain any other data type, including numbers, arrays, and even other objects.

Practical Patterns for Creating Objects

For simple objects that may only ever be used once in your application to store data, the above two methods can be used for creating objects.

Imagine you have an application that displays Employees and the details of each employee. All employees in your application have the following properties: id, name, designation, department, preferredLocation, getDetails and getpreferredLocations functions.

It would be quite tedious and counter-productive to type the following every time you want to create a new employee object.

var employee = {

id: 20984,

name: "Roger",

designation: "Project Manager",

department: "IT",

preferredLocation: ["Mumbai""Pune"],

getDetails : function () {

   console.log("This is a " + this.name + "working as " + this.designation);

}

getpreferredLocations: function () {

this.preferredLocation.forEach(function (eachCity) {

console.log("Works at:" + eachCity);

});

}

}

} 

If you have 10 employees then you will need to add the same code 10 times. And what if you need to make a change to the getpreferredLocations function? You will need to make the change in 10 places.

To solve these repetitive problems, software engineers have invented patterns (solutions for repetitive and common tasks) to make developing applications more efficient and streamlined.

Constructor Pattern for Creating Objects

function employee (emp_id, emp_name, emp_designation, emp_department, emp_preferredLocation) {

        this.id = emp_id;

        this.name = emp_name;

        this.designation = emp_designation;

        this.department = emp_department;

        this.preferredLocation = emp_preferredLocation;

        this.getDetails = function () {

            console.log("This is a " + this.name + "working as " + this.designation);

        }

        this.getpreferredLocations = function () {

            this.preferredLocation.forEach(function (eachCity) {

                console.log("Works at:" + eachCity);

            });

        }

    } 

With this pattern in place, it is very easy to create all Employees:

var softwareEngineerEmp = new employee(20989, "Dominic", "Software Engineer", "IT", ["Banglore", "Chennai"]);

softwareEngineerEmp.getDetails(); // This is a Dominic working as Software Engineer.

softwareEngineerEmp.getpreferredLocations();

// Works at:Banglore

// Works at:Chennai 

var AccountantEmp = new employee(19899, "Sam", "Accountant", "Account", ["Mumbai"]);

AccountantEmp.getDetails(); // This is a Sam working as Accountant.

AccountantEmp.getpreferredLocations(); // Works at: Mumbai


If you need to change the getDetails function then you only need to do it in one location. The pattern encapsulates all the functionalities and characteristics of the entire employee by making just the single employee function with inheritance.

Prototype Pattern for Creating Objects

 

function Employee () {

}

Employee.prototype.id = 20999;

Employee.prototype.name = "Kevin";

Employee.prototype.designation = "Delivery Head";

Employee.prototype.department = "IT";

Employee.prototype.preferredLocation = ["Banglore""USA"];

Employee.prototype.getDetails = function () {

console.log("This is a " + this.name + "working as " + this.designation);

Employee.prototype.getpreferredLocations = function () {

    this.preferredLocation.forEach(function (eachCity)  {

   console.log("Works at:" + eachCity);

    );

}    

And this is how we call the Employee() constructor in this prototype pattern:

var employee = new Employee();

employee.getDetails(); //  This is a Kevin working as Delivery Head.

employee.getpreferredLocations();

//  Works at:Banglore

//  Works at:USA

I have tried to cover the most basic features that will help to start with creating JavaScript objects. Thanks for your reading. Please provide your inputs and suggestions for the article.

Up Next
    Ebook Download
    View all
    Learn
    View all