Constructor

ยท

1 min read

A constructor is a special function that creates and initializes an object instance of a class.

In JavaScript, a constructor gets called when an object is created using the new keyword.

The purpose of a constructor is to create a new object and set values for any existing object properties.

In a constructor function this does not have a value.

example:

class Polygon {

constructor() {

this.name = 'Polygon';

} }

const poly1 = new Polygon();

console.log(poly1.name); // expected output: "Polygon"

A constructor enables you to provide any custom initialization that must be done before any other methods can be called on an instantiated object.

ย