Skip to content

JavaScript class constructor | Method

  • by

JavaScript class constructor Method is a special method used in classes to create and initialize an object instance of that class. This method is called automatically when a class is initiated.

constructor(argument0, argument1, ... , argumentN)

JavaScript will add an invisible and empty constructor method if you don’t add a constructor method in the class.

Note: You can’t use more than one constructor() method.

JavaScript class constructor

A simple example code constructor method must be defined before any other methods can be called on an instantiated object.

<!DOCTYPE html>
    class Polygon {
      constructor() {
        console.log("Constructor Method") = 'Polygon';

    const poly1 = new Polygon();



JavaScript class constructor

More Example

class Person {

      constructor(name) { = name;
      introduce() {
        console.log(`Hello, my name is ${}`);

    const otto = new Person('Otto');

Output: Hello, my name is Otto

A constructor can use the super keyword to call the constructor of the superclass.

function Animal(legs) {
      this.legs = legs;

    Animal.prototype.walk = function() {
      console.log('walking on ' + this.legs + ' legs');

    function Bird(legs) {, legs);

    Bird.prototype = Object.create(Animal.prototype);
    Bird.prototype.constructor = Animal; = function() {

    var pigeon = new Bird(2);

Here’s a basic example of a class constructor in JavaScript:

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

const person1 = new Person('Alice', 30);
const person2 = new Person('Bob', 25);

person1.sayHello(); // Output: Hello, my name is Alice and I am 30 years old.
person2.sayHello(); // Output: Hello, my name is Bob and I am 25 years old.

In this example, the Person class has a constructor that takes two parameters, name and age. When you create instances of the Person class using the new keyword, the constructor is called, and it initializes the name and age properties for each instance.

You can add other methods and properties to your class to define the behavior and characteristics of objects created from it. Class constructors are a fundamental concept in object-oriented programming in JavaScript and are widely used to create and manage objects.

Do comment if you have any doubts or suggestions on this JS class topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading