Edit Template
Edit Template

Constructor in JavaScript

In object-oriented programming (OOP), a constructor is a special function used to create and initialize new objects. In JavaScript, constructors allow you to create multiple objects with shared structure (properties and methods).

What Is a Constructor?

A constructor function is simply a regular function designed to initialize new objects using the new keyword. Here’s how it works:

				
					function Person(name, age) {
  this.name = name;
  this.age = age;
}

				
			
  • Person is the constructor function.

  • this.name and this.age refer to the properties of the object being created.

  • this always refers to the current instance.

Creating Objects Using a Constructor

You can create multiple objects from a constructor using the new keyword:

				
					let person1 = new Person("John", 30);
let person2 = new Person("Jane", 25);

				
			

Each object will have its own name and age values but share the same structure.

Adding Methods Inside Constructor

You can define methods inside the constructor so each object has its own version of the method:

				
					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.`;
  };
}

let p1 = new Person("Arshyan", 18);
console.log(p1.greet());
// Output: Hello, my name is Arshyan and I am 18 years old.

				
			

Tip: Defining methods inside the constructor gives each object its own copy of the method. To save memory, you can attach shared methods to the prototype (covered later).

Summary

  • A constructor is a function used to create objects with similar structure.

  • Use the new keyword to create a new instance.

  • The this keyword refers to the specific object being created.

  • You can define both properties and methods inside a constructor.

Scroll to Top