How to create objects in JavaScript

How to create objects in JavaScript

In this article, we will see the different ways to instantiate objects in JavaScript.

Originally published at https://www.geeksforgeeks.org

JavaScript is a flexible object-oriented language when it comes to syntax. In this article, we will see the different ways to instantiate objects in JavaScript.

Before we proceed it is important to note that JavaScript is a class-less language and the functions are used in a way so that they simulate a class.

Using functions as class:

One of the easiest way to instantiate an object in JavaScript. We define a classical JavaScript function and create an object of the function using new keyword. The properties and methods of function are created using the this keyword. 

<script> 
    // Function acting as a Class. 
    function copyClass(name, age) { 
        this.name = name; 
        this.age = age; 
        this.printInfo = function() { 
            console.log(this.name); 
            console.log(this.age); 
        } 
    } 


// Creating the object of copyClass  // and initializing the parameters.  var obj = new copyClass("Vineet", 20); 

// Calling the method of copyClass.  obj.printInfo();  </script> 

Output:

Vineet
20

Explanation: A class in OOPs have two major components, certain parameters and few member functions. In this method we declare a function similar to a class, there are two parameters, name and age ( the this keyword is used to differentiate the name and age of the class to the name and age of the arguments that are being supplied.) and a method printInfo that prints the value of these parameters. We then simple create an object obj of the copyClass, initialize it and call it’s method.

Using object literals:

Literals are smaller and simpler ways to define objects. Below we instantiate an object exactly same as the previous one just with the object literal.

<script> 
    // Creating Object. 
    var obj = { 
        name : "", 
        age : "", 
        printInfo : function() { 
            console.log(this.name); 
            console.log(this.age); 
        } 
    } 

// Initializing the parameters.  obj.name = "Vineet";  obj.age = 19; 

// Using method of the object.  obj.printInfo();  </script> 

Output:

Vineet
20

Explanation: This method works same along the line of the previous one but instead of bundling the parameters ( name and age ) and the method ( printInfo ) inside of a function, we bundle them in the object itself, initialize the object and simply use the methods.

Singleton using a function:

The third way presented is a combination of the other two that we already saw. We can use a function to define a singleton object.

<script> 
    // Creating singleton object. 
    var obj = new function() { 
        this.name = ""; 
        this.age = ""; 
        this.printInfo = function() { 
            console.log(this.name); 
            console.log(this.age); 
        }; 
    } 

// Initializing object.  obj.name = "Vineet";  obj.age = 20; 

// Calling method of the object.  obj.printInfo();  </script> 

Output:

Vineet
20

Explanation: This is a combination of the previous two methods, we bundle the methods and parameters inside a function but don’t declare a separate function for it (Like copyClass in method 1). Instead we simple use the function structure to declare a object.

Thanks for reading

If you liked this post, please do share/like it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading 

JavaScript Programming Tutorial - Full JavaScript Course for Beginners

How to Sort an Array of Objects in JavaScript

3 Ways to Clone Objects in JavaScript

Javascript Objects Tutorial Example




javascript objective-c function web-development

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

How to Find Ulimit For user on Linux

Explains how to find ulimit values of currently running process or given user account under Linux using the 'ulimit -a' builtin command.

MEAN Stack Tutorial MongoDB ExpressJS AngularJS NodeJS

MEAN Stack Tutorial MongoDB ExpressJS AngularJS NodeJS - We are going to build a full stack Todo App using the MEAN (MongoDB, ExpressJS, AngularJS and NodeJS). This is the last part of three-post series tutorial.

Creating RESTful APIs with NodeJS and MongoDB Tutorial

Creating RESTful APIs with NodeJS and MongoDB Tutorial - Welcome to this tutorial about RESTful API using Node.js (Express.js) and MongoDB (mongoose)! We are going to learn how to install and use each component individually and then proceed to create a RESTful API.

systemctl List All Failed Units/Services on Linux

Explains how to use the systemctl command to list all failed units or services on Debian, Ubuntu, CentOS, Arch, Fedora, and other Linux distros.

CentOS Linux 8.2 Released and Here is How to Upgrade it

CentOS Linux 8.2 (2004) released. This release adds corrections for security issues based upon RHEL 8.2 souce and here is how to upgrade it.