Skip to main content

How do you create a constructor function?

TL;DR​

To create a constructor function in JavaScript, define a regular function with a capitalized name to indicate it's a constructor. Use the this keyword to set properties and methods. When creating an instance, use the new keyword.

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

const john = new Person('John', 30);
console.log(john.age); // 30

How do you create a constructor function?​

Defining a constructor function​

A constructor function in JavaScript is a regular function that is used to create objects. By convention, the name of the constructor function starts with a capital letter to distinguish it from regular functions.

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

Using the this keyword​

Within the constructor function, the this keyword is used to refer to the object that will be created. Properties and methods can be assigned to this.

function Person(name, age) {
this.name = name;
this.age = age;
this.greet = function () {
console.log(
`Hello, my name is ${this.name} and I am ${this.age} years old.`,
);
};
}

Creating an instance​

To create an instance of the object, use the new keyword followed by the constructor function.

function Person(name, age) {
this.name = name;
this.age = age;
this.greet = function () {
console.log(
`Hello, my name is ${this.name} and I am ${this.age} years old.`,
);
};
}

const john = new Person('John', 30);
john.greet(); // Output: Hello, my name is John and I am 30 years old.

Adding methods to the prototype​

To save memory, it's a good practice to add methods to the constructor's prototype instead of defining them inside the constructor function.

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

Person.prototype.greet = function () {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
};

const jane = new Person('Jane', 25);
jane.greet(); // Output: Hello, my name is Jane and I am 25 years old.

Checking the instance type​

You can check if an object is an instance of a constructor function using the instanceof operator.

function Person(name, age) {
this.name = name;
this.age = age;
}
const jane = new Person('Jane', 25);

console.log(jane instanceof Person); // Output: true

Further reading​


Source: greatfrontend/top-javascript-interview-questions