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()
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>
<html>
<body>
  <script>
    class Polygon {
      constructor() {
        console.log("Constructor Method")
        this.name = 'Polygon';
      }
    }

    const poly1 = new Polygon();

    console.log(poly1.name);
  </script>
</body>
</html> 

Output:

JavaScript class constructor

More Example

class Person {

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

    const otto = new Person('Otto');
    otto.introduce();

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) {
      Animal.call(this, legs);
    }

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


    Bird.prototype.fly = function() {
      console.log('flying');
    }

    var pigeon = new Bird(2);
    pigeon.walk(); 
    pigeon.fly(); 

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.