DEV Community

Cover image for Constructor Function in JS
Vigneshwaran V
Vigneshwaran V

Posted on

Constructor Function in JS

Constructor Function?

A constructor function in JavaScript is a regular function used as a blueprint to create multiple objects with the same structure. It is explicitly executed using the new operator, which automatically creates and initializes a brand-new object instance.

Core Syntax and Conventions

There are two critical rules when writing constructor functions:

  • Capitalization: Name the function with a capital first letter (e.g., User, Car) to distinguish it from standard functions.

  • The new keyword: Always call the function using new. Failing to do so makes it execute like a regular function, which breaks the creation process.

In JavaScript, a constructor function is used to create and initialize objects.

Example

// constructor function
function Person () {
    this.name = "John",
    this.age = 23
}

// create an object
const person = new Person();

// print object attributes
console.log(person.name);
console.log(person.age);

// Output:
// John
// 23
Enter fullscreen mode Exit fullscreen mode

Here, Person() is an object constructor function. And, we use the new keyword to create an object from a constructor function.

Create Multiple Objects With Constructor Function

In JavaScript, you can create multiple objects from a constructor function. For example,

// constructor function
function Person () {
    this.name = "John",
    this.age = 23,

     this.greet = function () {
        console.log("hello");
    }
}

// create objects
const person1 = new Person();
const person2 = new Person();

// access properties
console.log(person1.name);  // John
console.log(person2.name);  // John
Enter fullscreen mode Exit fullscreen mode

In the above program, we created two objects (person1 and person2) using the same constructor function.


JavaScript Constructor Function Parameters

You can also create a constructor function with parameters. For example,

// constructor function with parameters
function Person (person_name, person_age, person_gender) {

   // assign parameter values to the calling object
    this.name = person_name,
    this.age = person_age,
    this.gender = person_gender,

    this.greet = function () {
        return (`Hi ${this.name}`);
    }
}

// create objects and pass arguments
const person1 = new Person("John", 23, "male");
const person2 = new Person("Sam", 25, "female");

// access properties
console.log(person1.name); // John
console.log(person2.name); // Sam
Enter fullscreen mode Exit fullscreen mode

In the above example, we have passed arguments to the constructor function during the creation of the object.

const person1 = new Person("John", 23, "male");
const person2 = new Person("Sam", 25, "female");
Enter fullscreen mode Exit fullscreen mode

This allows each object to have different properties:


this keyword in a Constructor Function (JavaScript)

In a constructor function, this refers to the new object being created.
When you use the new keyword:

  • A new empty object is created.

  • this points to that new object.

  • Properties are added to that object.

  • The object is returned automatically.

Example

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

let s1 = new Student("Vicky", 22);

console.log(s1);
Enter fullscreen mode Exit fullscreen mode

Output

{
  name: "Vicky",
  age: 22
}

Enter fullscreen mode Exit fullscreen mode

How this works here

function Student(name, age) {
    this.name = name; // s1.name = "Vicky"
    this.age = age;   // s1.age = 22
}
Enter fullscreen mode Exit fullscreen mode

When this line runs:

let s1 = new Student("Vicky", 22);
Enter fullscreen mode Exit fullscreen mode

JavaScript internally does something similar to:

let s1 = {};
s1.name = "Vicky";
s1.age = 22;
Enter fullscreen mode Exit fullscreen mode

So this refers to s1.

Constructor with Methods

function Student(name, age) {
    this.name = name;
    this.age = age;

    this.display = function() {
        console.log(this.name, this.age);
    };
}

let s1 = new Student("Vicky", 22);

s1.display();
Enter fullscreen mode Exit fullscreen mode

Output

Vicky 22
Enter fullscreen mode Exit fullscreen mode

In an object method call (object.method()), this refers to the object before the dot (.).

  • In our program, both times this ends up referring to s1, but for different reasons.

  • In Student(), this refers to s1 because of the new keyword.

  • In display(), this refers to s1 because s1 called the method using s1.display().


Definition: In a constructor function, this refers to the newly created object and is used to initialize its properties and methods.


Refernce

https://www.programiz.com/javascript/constructor-function

Top comments (0)