Different ways to create objects

Create Objects in Different Ways

In this example, you will learn to create JavaScript objects in different ways.

To understand this example, you should have the knowledge of the following JavaScript programming topics:

JavaScript Objects

JavaScript Constructor Function


You can create an object in three different ways:


1)Using object literal

2)By creating instance of Object directly

3)By using constructor function


Example 1: Using object literal



In this program, we have created an object named person.

You can create an object using an object literal. An object literal uses { } to create an object directly.

An object is created with a key:value pair.

You can also define functions, arrays and even objects inside of an object. You can access the value of the object using dot . notation.


The syntax for creating an object using instance of an object is:


Example 2: Create an Object using Instance of Object Directly


Here, the new keyword is used with the Object() instance to create an object.


Example 3: Create an object using Constructor Function



In the above example, the Person() constructor function is used to create an object using the new keyword.


new Person() creates a new object.

 

Post a Comment

Previous Post Next Post