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 define 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);

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

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.