JavaScript OOPs Constructor Method - JavaScript Tutorial

JavaScript OOPs Constructor Method

BLUF: This tutorial on JavaScript OOPs Constructor Method provides an in-depth look at JavaScript's core features. It includes practical examples and code snippets to help you master modern JS development.
Key Discovery: JavaScript OOPs Constructor Method

Understanding JavaScript OOPs Constructor Method is crucial for building dynamic, interactive web applications. Explore the examples below to see it in action.

A constructor method in JavaScript is a distinct kind of method designed for the purpose of initializing and generating an object. This method is invoked at the moment memory is assigned for the creation of an object.

Points to remember

  • The constructor keyword is used to declare a constructor method.
  • The class can contain one constructor method only.
  • JavaScript allows us to use parent class constructor through super keyword.
  • Constructor Method Example

Let’s examine a straightforward illustration of a constructor method.

Example

<script>

class Employee {

  constructor() {

    this.id=101;

    this.name = "Martin Roy";

  } 

}

var emp = new Employee();

document.writeln(emp.id+" "+emp.name);

</script>

Output:

Output

101 Martin Roy

Constructor Method Example: super keyword

The super keyword serves the purpose of invoking the constructor of the parent class. Let’s examine an example.

Example

<script>

class CompanyName

{

  constructor()

  {

    this.company="Example";

  }

}

class Employee extends CompanyName {

  constructor(id,name) {

   super();

    this.id=id;

    this.name=name;

  } 

}	

var emp = new Employee(1,"John");

document.writeln(emp.id+" "+emp.name+" "+emp.company);

</script>

Output:

Output

1 John C# Tutorial

Note - If we didn't specify any constructor method, JavaScript use default constructor method.

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience