In JavaScript, there are four methods to use to create an object:
- Object literals
- New operator or constructor
- Object.create method
- Class
In this post, we will learn each of these methods.
Object literals
An object literal, also called an object initializer, is a comma-separated set of paired names and values. You can create an object literal as shown below:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var car = { | |
model: 'bmw', | |
color: 'red', | |
price: 2000 | |
} | |
console.log(JSON.stringify(car)); |
You can add properties dynamically in an object, including after you have created the object. Here we add the dynamic property car.type:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var car = { | |
model: 'bmw', | |
color: 'red', | |
price: 2000 | |
} | |
console.log(JSON.stringify(car)); | |
car.type = 'manual'; // dynamic property console.log(JSON.stringify(car)); |
The object literal is a simple expression that creates an object each time the statement that it appears in is executed in the code. You can also use Object.defineProperty to create properties in the object literal as shown below:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var car = { | |
model: 'bmw', | |
color: 'red', | |
price: 2000 | |
} | |
Object.defineProperty(car, "type", { | |
writable: true, | |
enumerable: true, | |
configurable: false, | |
value: 'gas' | |
}); | |
console.log(car.type); //gas |
The main advantage of using Object.defineProperty is that you can set values for object property descriptors or modify existing properties. You can learn more about Object Property Descriptor here.
New Operator or Constructor
The second way to create an object is to use the constructor function. If you call a function using a new operator, the function acts as a constructor and returns an object. Consider the following code:
Leave a Reply