What is a Constructor in JavaScript?
Last Updated :
24 Sep, 2024
A constructor in JavaScript is a special function that is used to create and initialize objects. When we want to create multiple objects with similar properties and methods, the constructor is used as a blueprint to create similar objects. This is useful when you want to create multiple objects with the same structure but different values. Constructors help us to make sure each new object is created with consistent structure which helps us achieve code modularity and cleanliness.
In simple, the constructors are like templates for creating objects. They define the properties and methods that each object will have, so we don't have to repeat the same code every time we create a new object. Without a constructor we would need to define each object manually, so to remove redundancy and make sure that consistency is preserved, we use constructors.
These are the following topics that we are going to discuss:
Basic Constructor Function in JavaScript
Before ES6 classes, the main way to create objects in JavaScript was by using function constructors. A function constructor is a regular function that we use with the new keyword to create object instances.
Syntax:
function User(name, age) {
this.name = name;
this.age = age;
}
Use of the new Keyword to Create Object Instances
To create an object using a function constructor, we follow these steps:
- Define a function that acts as a constructor.
- Use the this keyword inside the constructor to set properties and methods.
- Use the new keyword to create an instance of the object.
Syntax:
function ConstructorName(parameter1, parameter2) {
this.property1 = parameter1;
this.property2 = parameter2;
// Additional properties or methods
}
When we use the new keyword, JavaScript creates a new object, sets its prototype to the constructor's prototype. After that it assigns this to the new object.
Example: In this example, we defined a Person constructor function that takes name and age as parameters. Using new Person('Alice', 30), we created a new object person1 with those properties.
JavaScript
function Person(name, age) {
this.name = name;
this.age = age;
this.greet = function () {
return `Hello, my name is ${this.name} and I am ${this.age} years old.`;
};
}
const person1 = new Person('Alice', 30);
console.log(person1.greet());
// Output: Hello, my name is Alice and I am 30 years old.
OutputHello, my name is Alice and I am 30 years old.
This Keyword in Constructors
In JavaScript, the 'this' keyword inside a constructor refers to the object that is being created by the constructor. It help us to set properties and methods for that object. The this keyword is automatically bound to the new object that is created when using the new keyword.
When a constructor is called with the new keyword, this becomes a reference to the new object. We can use it to set properties and define methods that the object will have.
Example: Here, this.brand and this.model refer to the brand and model properties of the car1 object. The getDetails method can access these properties using this.
JavaScript
function Car(brand, model) {
this.brand = brand;
this.model = model;
this.getDetails = function () {
return `Car: ${this.brand} ${this.model}`;
};
}
const car1 = new Car('Toyota', 'Corolla');
console.log(car1.getDetails());
// Output: Car: Toyota Corolla
OutputCar: Toyota Corolla
Built-in and Custom Constructors in JavaScript
JavaScript provides built-in constructors like Array(), Date(), and Object(). These constructors create instances of built-in object types. We can also create custom constructors to define our own object types.
Built-in Constructor
Built-in constructors are predefined functions in JavaScript that help us to create instances of native objects.
Example: Here, Array() and Date() are built-in constructors that create an array and a date object, respectively.
JavaScript
const myArray = new Array(1, 2, 3);
console.log(myArray); // Output: [1, 2, 3]
const myDate = new Date();
console.log(myDate); // Output: Current date and time
Output[ 1, 2, 3 ]
2024-09-23T11:29:12.062Z
Creating Custom Constructors
Custom constructors allow us to define our own object types with specific properties and methods.
Example: In this example, the Book constructor creates a custom object with title and author properties.
JavaScript
function Book(title, author) {
this.title = title;
this.author = author;
}
const book1 = new Book('1984', 'George Orwell');
console.log(book1);
// Output: Book { title: '1984', author: 'George Orwell' }
OutputBook { title: '1984', author: 'George Orwell' }
Classes and constructor() in ES6
ES6 introduced the class keyword, which provides a clearer and more concise syntax for creating objects and deals with inheritance. The constructor() method inside a class is used to initialize object properties. In ES6, we define a constructor using the constructor() method inside a class. This method is automatically called when a new instance of the class is created.
Example: In this example, Person is a class, and the constructor() method initializes the name and age properties.
JavaScript
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
return `Hello, I am ${this.name} and I am ${this.age} years old.`;
}
}
const person2 = new Person('Bob', 25);
console.log(person2.greet());
// Output: Hello, I am Bob and I am 25 years old.
OutputHello, I am Bob and I am 25 years old.
Constructor vs Factory Functions
Constructors are used to create objects using the new keyword while factory functions are regular functions that return an object without using new keyword.
Key Differences:
- Constructor Functions: Use new to create an object and set this to the new object. They are typically used for creating instances of a particular type.
- Factory Functions: Return an object directly without using new. They provide greater flexibility and don't require the new keyword.
Example: Here, createCar is a factory function that returns a new object without using new.
JavaScript
function createCar(brand, model) {
return {
brand: brand,
model: model,
getDetails: function() {
return `${this.brand} ${this.model}`;
}
};
}
const car3 = createCar('Ford', 'Mustang');
console.log(car3.getDetails()); // Output: Ford Mustang
Common Mistakes with Constructors
Now we will look at some common mistakes that developers often make when working with constructors, and how to avoid them.
Forgetting the new Keyword
One of the most frequent mistakes is forgetting to use the new keyword when creating an object with a constructor function. When we omit new, the constructor function doesn't behave as expected. Instead of creating a new object, the this keyword inside the function refers to the global object (or undefined in strict mode), which can cause unexpected results and bugs in our code.
Example: In this example, because we forgot the new keyword, Phone() does not create a new object. Instead, this.brand refers to the global object, and myPhone ends up being undefined. This can lead to unexpected behavior, as the global object is modified unintentionally.
JavaScript
function Phone(brand, model) {
this.brand = brand;
this.model = model;
}
const myPhone = Phone('Apple', 'iPhone 13');
console.log(myPhone);
// Output: undefined
console.log(window.brand);
// Output: Apple (in browsers)
// `brand` property is now
// set on the global object instead of a new object.
Correction: Here, we use the new keyword to correctly create a new Phone object. Now, myPhone is an instance of the Phone constructor, with its own brand and model properties.
JavaScript
function Phone(brand, model) {
this.brand = brand;
this.model = model;
}
const myPhone = new Phone('Apple', 'iPhone 13');
console.log(myPhone);
OutputPhone { brand: 'Apple', model: 'iPhone 13' }
Misplacing Methods Inside the Constructor
Another common mistake is defining methods inside the constructor function instead of using the prototype. This can lead to memory inefficiency, as each instance will have its own copy of the method.
Example: In this case, the greet method is redefined for every instance of Person, leading to unnecessary duplication of the same function
JavaScript
function Person(name) {
this.name = name;
this.greet = function () {
return `Hello, my name is ${this.name}`;
};
}
const person1 = new Person('Alice');
const person2 = new Person('Bob');
console.log(person1.greet === person2.greet);
Correction: By using the prototype, both instances share the same greet method, making our code more efficient.
JavaScript
function Person(name) {
this.name = name;
}
Person.prototype.greet = function () {
return `Hello, my name is ${this.name}`;
};
const person1 = new Person('Alice');
const person2 = new Person('Bob');
console.log(person1.greet === person2.greet);
Incorrect Use of Arrow Functions as Constructor Methods
Arrow functions do not have their own this binding, so using them as methods inside a constructor can lead to unexpected results.
Example: In this example, the getBrand method is defined using an arrow function, so this.brand does not refer to the Car instance. Instead, it refers to the surrounding lexical context, which in this case is likely the global object.
JavaScript
function Car(brand) {
this.brand = brand;
this.getBrand = () => {
return this.brand;
};
}
const car1 = new Car('Toyota');
console.log(car1.getBrand());
Correction: By using a regular function, this correctly refers to the instance of the Car object.
JavaScript
function Car(brand) {
this.brand = brand;
this.getBrand = function () {
return this.brand;
};
}
const car1 = new Car('Toyota');
console.log(car1.getBrand());
Conclusion
By using constructors, we can create multiple objects with the same properties and methods without writing the code for each object separately which makes our code scalable and maintainable. Constructors are very important when it comes to JavaScript Object-oriented programming. It provides a structured way to create and initialize objects which help us to define properties and methods for object instances. By mastering constructors, we can use the full power of OOPs in JavaScript which will help us to create flexible and efficient applications.
Similar Reads
What is the (function() { } )() construct in JavaScript?
If you've ever played around with JavaScript, you might have seen this expression. It's like a strange set of symbols, but it has a special name that is an immediately invoked function expression, or IIFE. In this article, we will understand each element of the expression as well as the functionalit
3 min read
JavaScript WeakSet() Constructor
JavaScript WeakSet Constructor is used to create a weakset that is similar to the set as it does not contain duplicate objects. It is different from the set as it stores a collection of weakly held objects instead of an object of a particular type. We can only create a WeakSet with the new keyword o
2 min read
JavaScript Set() Constructor
The Javascript Set constructor is used to create Set objects. It will create a set of unique values of any type, whether primitive values or object preferences. It returns the new Set object. It mainly helps in creating a new set of objects which contains unique elements. Syntax:new Set()new Set(ite
3 min read
JavaScript Map() Constructor
The Map() constructor is used to create Map objects in JavaScript. The map is a data structure that stores elements as a key, value pair. Syntax:new Map()new Map(iterable)Parameters:iterable: An iterable object used for iterating through elements, stored as a key, value pair.Return value:A new Map o
3 min read
What is arguments in JavaScript ?
In this article, we will learn about arguments object in JavaScript in detail. Like what is arguments object in JavaScript and then we will discuss some programs using arguments object. We will discuss the following points: What is the arguments in JavaScript?Programs related to arguments object.The
3 min read
JavaScript Object Constructors
An object is the collection of related data or functionality in the form of key. These functionalities usually consist of several functions and variables. All JavaScript values are objects except primitives. const GFG = { subject : "programming", language : "JavaScript",}Here, subject and language a
4 min read
JavaScript Intl ListFormat() Constructor
JavaScript Intl.ListFormat() Constructor is used for creating Intl.ListFormat object. This constructor is created using the new keyword. If we create the constructor without the new keyword it will give a TypeError. Syntax: new Intl.ListFormat(loc, opt) Parameters: It has two parameters both are opt
1 min read
JavaScript Function() Constructor
The JavaScript Function() constructor is used to create new function objects dynamically. By using the Function() constructor with the new operator, developers can define functions on the fly, passing the function body as a string. This allows for greater flexibility in situations where functions ne
2 min read
Multiple Class Constructors in JavaScript
Classes were introduced in ES6 and along with it the concepts of Object Oriented Programming were implemented. Even with all these new features, JavaScript does not allow constructor overloading. So, we cannot create multiple constructors for a single class in JavaScript but there are some methods w
3 min read
JavaScript Array() Constructor
The Array() constructor is used to create Array objects and the array constructor can be called with or without a new keyword, both can create a new Array. Syntax:new Array(Value1, Value2, ...);new Array(ArrayLength);Array(Value1, Value2, ...);Array(ArrayLength);Parameters: ValueN: An array initiali
2 min read