JavaScript Constructor Method (original) (raw)

Last Updated : 15 Feb, 2025

A constructor in JavaScript is a special function used to create and initialize objects. It sets up object properties and is typically invoked using the new keyword. Constructors allow for the creation of multiple instances with similar properties and methods.

**In JavaScript, constructors can be defined in two main ways

1. **Function Constructor Method (Before ES6)

Before ES6, JavaScript used constructor functions to create and initialize objects. A constructor function is essentially a regular function that is invoked using the new keyword. Here’s how you define a constructor function.

JavaScript ``

function Car(make, model, year) { this.make = make; this.model = model; this.year = year; this.getCarInfo = function () { return ${this.year} <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>t</mi><mi>h</mi><mi>i</mi><mi>s</mi><mi mathvariant="normal">.</mi><mi>m</mi><mi>a</mi><mi>k</mi><mi>e</mi></mrow><annotation encoding="application/x-tex">{this.make} </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6944em;"></span><span class="mord"><span class="mord mathnormal">t</span><span class="mord mathnormal">hi</span><span class="mord mathnormal">s</span><span class="mord">.</span><span class="mord mathnormal" style="margin-right:0.03148em;">mak</span><span class="mord mathnormal">e</span></span></span></span></span>{this.model}; }; }

let myCar = new Car('Toyota', 'Camry', 2020); console.log(myCar.getCarInfo());

``

2. Class Constructor Method (ES6 and Beyond)

With the introduction of ES6, JavaScript introduced class syntax, making object-oriented programming more structured and readable. Classes provide a more modern and organized way to define constructors.

JavaScript ``

class Car { constructor(make, model, year) { this.make = make; this.model = model; this.year = year; }

getCarInfo() {
    return `${this.year} <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>t</mi><mi>h</mi><mi>i</mi><mi>s</mi><mi mathvariant="normal">.</mi><mi>m</mi><mi>a</mi><mi>k</mi><mi>e</mi></mrow><annotation encoding="application/x-tex">{this.make} </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6944em;"></span><span class="mord"><span class="mord mathnormal">t</span><span class="mord mathnormal">hi</span><span class="mord mathnormal">s</span><span class="mord">.</span><span class="mord mathnormal" style="margin-right:0.03148em;">mak</span><span class="mord mathnormal">e</span></span></span></span></span>{this.model}`;
}

}

let myCar = new Car('Honda', 'Civic', 2022); console.log(myCar.getCarInfo());

``

How constructor works in JavaScript?

new keyword in JavaScript

The new keyword in JavaScript is used to create an object out of a constructor function in a class representation and also from the normal function’s.

JavaScript `

//Object from a function function prints(name,age) { this.name=name this.age=age } const result=new prints('Pranjal',21) console.log(result) //Object from a class class Person{ constructor(name,age) { this.name=name this.age=age } } const result1=new Person('Saurabh',30) console.log(result1)

`

Output

prints { name: 'Pranjal', age: 21 } Person { name: 'Saurabh', age: 30 }

Object.create() function in JavaScript

In real life prototype means a copy of something same is the case in JavaScript here prototype means a copy of a object, function or class. Here in this scenario Object.create() is used to create a copy of a object and to copy all it’s properties into itself without the help of constructor function.

JavaScript `

const obj={ name:'Pranjal', age:21 } const obj1=Object.create(obj) obj1.class='10th' console.log(obj1.name)

`

Object Factory Functions

A factory function is a regular function that returns a new object, making it a simple and reusable way to create multiple instances without using new.

JavaScript ``

function createPerson(name, age) { return { name: name, age: age, greet: function() { console.log(Hello, my name is ${this.name}); } }; }

const person1 = createPerson("Pranjal", 30); const person2 = createPerson("Vivekam", 25);

person1.greet(); person2.greet();

``

Output

Hello, my name is Pranjal Hello, my name is Vivekam

Constructor with default values

A constructor with default values allows you to specify default values for properties if no values are provided during object creation. This helps in ensuring that the object always has valid properties, even if some arguments are missing.

JavaScript `

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

const person1 = new Person("Pranjal", 30); const person2 = new Person("Amar");
const person3 = new Person();

console.log(person1);
console.log(person2); console.log(person3);

`

Output

Person { name: 'Pranjal', age: 30 } Person { name: 'Amar', age: 0 } Person { name: 'Unknown', age: 0 }

Constructor with method on prototypes

In JavaScript, you can add methods to the prototype of a constructor, allowing all instances created from that constructor to share the same method. This helps in optimizing memory usage, as the method is not recreated for each instance.

JavaScript ``

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

Person.prototype.greet = function() { console.log(Hello, my name is <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mrow><mi>t</mi><mi>h</mi><mi>i</mi><mi>s</mi><mi mathvariant="normal">.</mi><mi>n</mi><mi>a</mi><mi>m</mi><mi>e</mi></mrow><mi>a</mi><mi>n</mi><mi>d</mi><mi>I</mi><mi>a</mi><mi>m</mi></mrow><annotation encoding="application/x-tex">{this.name} and I am </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6944em;"></span><span class="mord"><span class="mord mathnormal">t</span><span class="mord mathnormal">hi</span><span class="mord mathnormal">s</span><span class="mord">.</span><span class="mord mathnormal">nam</span><span class="mord mathnormal">e</span></span><span class="mord mathnormal">an</span><span class="mord mathnormal">d</span><span class="mord mathnormal" style="margin-right:0.07847em;">I</span><span class="mord mathnormal">am</span></span></span></span>{this.age} years old.); };

const person1 = new Person("Pranjal", 30); const person2 = new Person("Amar", 25);

person1.greet();
person2.greet();

``

Output

Hello, my name is Pranjal and I am 30 years old. Hello, my name is Amar and I am 25 years old.

Constructor with inheritance

This code demonstrates how inheritance in classes allows a child class to inherit both properties and methods from a parent class constructor. The child class (two) inherits the name property from the parent class (one) using the super() keyword.

JavaScript ``

class one{ constructor(name) { this.name=name } greet() { return Hello ${this.name} } } class two extends one{ constructor(name,age) { super(name) this.age=age } greet1(){ return Your age is ${this.age} } } const person1=new one('Pranjal') const person2=new two('Pranav',21) console.log(person2.greet())

``

Advantages of constructor

Conclusion

JavaScript constructors help developers create reusable, consistent, and well-structured objects. They simplify object initialization, support inheritance, and ensure cleaner code, making them essential in object-oriented programming. Understanding and using constructors effectively leads to more maintainable and efficient code in JavaScript.