Easy JavaScript Part 13: Four Ways to Create Objects in JavaScript
We continue our exploration of the ins and outs of JavaScript, by taking a look at the several ways devs can create objects.
Join the DZone community and get the full member experience.
Join For FreeIn 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:
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:
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:
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:
function Car(model, color) {
this.model = model;
this.color = color;
}
var c1 = new Car('BMW', 'red');
console.log(c1.model);
This method of creating an object is also called the Constructor Invocation Pattern. There are two steps to work with the constructor function:
- Create a function, which will define the object type.
- Create an instance of an object using a new operator.
To create a Student object, first, create a function as shown below. In this example, this represents the object being created, so name and age will be properties of the newly created object.
function Student(name, age) {
this.name = name;
this.age = age;
}
Next, create instances of the Student object type as shown below:
var s1 = new Student('foo', 7);
console.log(s1.name);
var s2 = new Student('koo', 9);
console.log(s2.name);
You can use the instanceof
operator to find types of the instance and determine whether s1 is an instance of the Student object, as shown below:
var s1 = new Student('foo', 9);
console.log(s1 instanceof Student);
You can also use Object.defineProperty
to create properties in the constructor function, as shown below:
function Car(model) {
Object.defineProperty(this, "model", {
writable: true,
enumerable: true,
configurable: false,
value: model
});
}
var myCar = new Car("Audi A3");
console.log(myCar.model); // Audi A3
The main advantage of using Object.defineProperty
is that you can set values for object property descriptors. You can learn more about Object Property Descriptors here.
Object.create Method
You can also create new objects using the Object.create()
method, which allows you to specify the prototype object and the properties. For example:
var Car = {
model: 'BMW',
color: 'red'
}
You can use the Car
object as a prototype to create another object, as shown below:
var ElectricCar = Object.create(Car);
console.log(ElectricCar.model); // BMW
In this example, you have created an object called ElectricCar
using the Car
object as a prototype, so the ElectricCar
object will have all the properties of the Car
object. You can also add properties as shown below:
var ElectricCar = Object.create(Car, {
type: {
value: 'Electric',
writable: true,
configurable: false,
enumerable: true
}
});
console.log(ElectricCar.type); // Electric
Properties should be passed as objects and can be set using the property descriptor. You can also use the Object.create
method to create inheritance between objects.
Class
ECMAScript 6 introduced the class keyword to create classes in JavaScript. Now you can use the class attribute to create a class in JavaScript instead of a function constructor, and use the new operator to create an instance. Consider the following code:
class Car {
constructor(maker, price) {
this.maker = maker;
this.price = price;
}
getInfo() {
console.log(this.maker + " costs : " + this.price);
}
}
You can use the Car
class to create objects as shown below:
var car1 = new Car("BMW", 100);
car1.getInfo();
var car2 = new Car("Audi", 150);
car2.getInfo();
You can learn more about class here.
Conclusion
There are four ways to create an object in JavaScript - using object literals, using the function constructor, using the Object.create
method, and using the class keyword (which is almost the same as using a function constructor). The Object.create
method is very useful when you need to create an object using an existing object as a prototype.
In the next post, we will dive into other aspects of JavaScript!
Published at DZone with permission of Dhananjay Kumar, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments