javascript
  1. javascript-constructor-method

JavaScript Constructor Method

The constructor method is a special method in JavaScript that is used to create and initialize objects created by a class. It is called automatically when an object is created using the new keyword. This method is one of the fundamental building blocks of object-oriented programming (OOP) in JavaScript. In this page, we will learn about the syntax, example, output, explanation, use, important points, and summary of the constructor method.

Syntax

class ClassName {
  constructor(parameters) {
    // code to initialize properties of the object
  }
}
  • ClassName: The name of the class that the constructor method belongs to.
  • parameters: The parameters that the constructor method accepts.

Example

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

let person1 = new Person('John', 32);
let person2 = new Person('Alice', 25);

console.log(person1); // output: { name: 'John', age: 32 }
console.log(person2); // output: { name: 'Alice', age: 25 }

Explanation

In the example above, we define a class called Person with two properties: name and age. We use the constructor method to initialize these properties when an object of this class is created using the new keyword. We pass two arguments to the constructor method: name and age. Inside the constructor method, we use the this keyword to refer to the current object being created. We assign the values of name and age to the this.name and this.age properties, respectively. After the objects person1 and person2 are created, we use console.log() to output their values to the console.

Use

The constructor method is used to initialize the properties of an object created by a class. It is automatically called when an object is created using the new keyword. Inside the constructor method, you can set the initial values of the properties of the object using the arguments passed to the method.

Important Points

  • The constructor method is a special method in JavaScript that is used to create and initialize objects created by a class.
  • It is called automatically when an object is created using the new keyword.
  • The constructor method is used to initialize the properties of an object.
  • Inside the constructor method, you can set the initial values of the properties of the object using the arguments passed to the method.
  • The constructor method is one of the fundamental building blocks of object-oriented programming (OOP) in JavaScript.

Summary

In this page, we learned about the constructor method in JavaScript. We learned its syntax, example, output, explanation, use, important points, and summary. The constructor method is a fundamental building block of object-oriented programming in JavaScript. It is used to create and initialize objects created by a class. By using the constructor method, you can set the initial values of the properties of an object.

Published on: