JavaScript Objects

Objects provide a way of organizing variables and functions into logical groups.

The variables are called properties and functions are called methods of the object.

JavaScript has several predefined objects like Math, String etc. However, sometimes we may need to create custom objects.
 

Creating Objects in JavaScript

There are two options to create custom objects: which you choose depends upon whether you need to create a single custom object or multiple instances of the same custom object.
 

Creating a single Custom Object

To create a single custom object, use this approach.

In this approach, we list the properties and methods of the object, separated by commas. For each property and method, we assign a value using a colon (:) instead of the assignment operator.

Following code creates a hotel object following approach.

var employee = {
  firstName: "Joseph",
  lastName: "Doe",
  department: "IT",
  hireDate: new Date(),
  getName: function() {
      return this.lastName + ", "+this.firstName;
    } // No comma.
};

console.log("Employee name = " + employee.getName());

 
Output :

Employee name = Doe, Joseph
 

Creating multiple instances of a Custom Object

In this approach, first we create a Constructor function (like Employee() shown below).

Inside the function we create variables and methods and refer them with this (current object).

function Employee(firstName,lastName,department){
  this.firstName = firstName;
  this.lastName = lastName;
  this.department = department;
  this.getEmployee= function() {
      return "Name : " + this.firstName + " " + this.lastName + ", Department : " + this.department;
    } ;
}

 
To create objects from the above constructor function, we use the new keyword and pass the needed parameters.

var emp1 = new Employee("John","Doe","IT");
console.log("Employee 1 Details = " + emp1.getEmployee());
    
var emp2 = new Employee("Dave","Mathias","HR");
console.log("Employee 2 Details = " + emp2.getEmployee());

 
Output:

create javascript custom object

 

© 2016, https:. All rights reserved. On republishing this post, you must provide link to original post

Leave a Reply.. code can be added in <code> </code> tags