How to create objects in javascript / Everything about javascript objects

 

 

What is an Object?

An object is an entity which has some attributes(or fields or properties) and functions. Attributes represent state of an object and functions represent the task that can be done by the object. Attributes are key-value pairs and functions may or may not return a value. Also, objects in javascript are enclosed between curly braces({ and }).
When compared to real life, a mobile phone is an object with attributes such as color, size, weight etc. and functions such as switchOn, switchOff, call, touch etc.
Objects are assigned to variables just like ordinary variables. An example of an object is

var employee = {
      id: ‘1’,
      name: ‘Employee’,
      getId: function getId() {
                 return id;
             }   
};

Here employee is an object having two fields and a function getId. Note that the object is assigned to a variable just like any other variable.

In javascript, objects are variables that contain many values


Accessing fields of an Object

Fields of a javascript object can be accessed in two ways.

      1. Using dot (.) operator
          Access any property by using a dot between object name and the required property such as employee.id.

      2. Using property name as a string
          Access the property by putting its name between square brackets enclosed inside quotes and preceded by the name of the object. Example, employee['id']

When accessing functions of javascript objects, only dot operator method can be used. Syntax is

variable(or object name).functionName()


How to create an Object?

There are various ways to create an object in javascript. All of those are discussed below.

 

Method 1 : Using Direct Assignment

This is the simplest method to create an object. Define a variable, assign it a collection of key-value pairs enclosed between braces. Key-value pairs themselves will be separated by a comma. Example,

var website = { name: ‘codippa’, domain: ‘codippa.com’};

It is not necessary to place all key-value pairs in one line, they may span over multiple lines.
A key can defined a function in place of a value as

var website = {
    name       : ‘codippa’,
    domain     : ‘codippa.com’
    printName  : function() {
                    console.log(‘www.codippa.com’);
                 }
};

Properties of this object can be accessed using any of the methods explained previously as website.name or website['name']. In order to call the function, only dot operator convention can be used followed by parenthesis as website.printName();

Method 2 : Using Object creator function

Suppose you have an employee object with properties for first and last names, age, gender, address etc. In order to create an object of employee, you need to write a syntax of the form:

var employee = {
        firstName: ‘abc’,
        lastName: ‘xyz’,
        age: 25
        ……
};

Now imagine there are 50 employees and you need to create an object of employee for each employee. How much redundant code you need to write?

There is another way in which most of the code can be reused, thus preventing you from writing extra lines of code and letting you create as many objects as you want via functions.
Create a function to make objects, assign them values and return the newly created objects. You need to just call the function with required values and assign the return value to a variable, which will be the object reference or name of object as shown below.

function createEmployee(firstName, lastName, age, address) {
       var empObject = {}; // create an empty object
       // create properties dynamically and assign them values
       empObject.firstName = firstName;
       empObject.lastName = lastName;
       empObject.age = age;
       empObject.address = address; // and so on
       return empObject // return the newly created object
}
// create employee objects
var empOne = createEmployee(‘abc’, ‘xyz’, 23, ‘India’);
var empTwo = createEmployee(‘def’, ‘tuv’, 25, ‘USA’);
var empThree = createEmployee(‘ghi’, ‘qrs’, 27, ‘England’);

 

Method 3: Using Constructor functions

Javascript supports creating objects via constructor functions. Constructor functions are similar to normal functions and are used for creating objects. Difference lies in their way of calling. Unlike normal functions these functions are called by preceding new before their names. This lets javascript know that this function is responsible for creating objects. This method is similar to the previous method except there is no need to declare an empty object and return the created object from the function. Thus, the above function can be modified as

function createEmployee(firstName, lastName, age, address) {
       // create properties dynamically and assign them values
       this.firstName = firstName;
       this.lastName = lastName;
       this.age = age;
       this.address = address; // and so on
}
// create employee objects using constructor function
var empOne = new createEmployee(‘abc’, ‘xyz’, 23, ‘India’);
var empTwo = new createEmployee(‘def’, ‘tuv’, 25, ‘USA’);
var empThree = new createEmployee(‘ghi’, ‘qrs’, 27, ‘England’);

Notice that the function which creates object is similar to the previous method but it does not create any empty object and does not return anything. Instead, it creates properties using this. When function call is preceded with new, javascript knows that the responsibility of this function is to create objects. Thus, this inside the function refers to the current object which is created by javascript behind the scenes.

Method 4: Using Object class

In javascript, every object is of type Object. Thus, it is also possible to directly create an Object and assign properties to it as shown below.

var empObj = new Object();
empObj.firstName = ‘abc’;

When the above object is printed, this is the output

Object { firstName: ‘abc’ }

Creating Properties After Object Creation

In javascript, you can add properties and functions to an object even after it is created. This means that it is not necessary to provide all the properties at the time of creating an object, they may be added later. Same applies to functions. Thus, for our website object which had properties name and domain and a function printName, we can easily do

website.host = ‘localhost’;

This adds a new property named host to the object and it can be accessed using any of the accessing methods(dot operator or name of property). We have already done this in earlier examples.