DEV Community

Sasireka
Sasireka

Posted on

Constructor in Javascript

What is a Constructor in JavaScript?

  • A constructor is a special function that creates and initializes an object instance of a class. In JavaScript, a constructor gets called when an object is created using the new keyword.

  • The purpose of a constructor is to create a new object and set values for any existing object properties.

JavaScript Constructor Examples

Here’s a few examples of constructors in JavaScript:

Using the "this" Keyword

  • When the this keyword is used in a constructor, it refers to the newly created object:
function User() {
    this.name = 'Sasi';
}

var user = new User();
console.log(user)
Enter fullscreen mode Exit fullscreen mode

Create Multiple Objects

  • In JavaScript, multiple objects can be created in a constructor:
function User() {
this.name = 'Sasi';
}

var user1 = new User();
var user2 = new User();
console.log(user1)
console.log(user2)
Enter fullscreen mode Exit fullscreen mode

Constructor with Parameters

  • A constructor can also have parameters:
function User (name, age) {
    this.name = name;
    this.age = age;
}

var user1 = new User('Sasi', 23);
var user2 = new User('Keerthi', 24);
console.log(user1)
console.log(user2)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)