Constructor() in class{}: why is it needed?

Hi, basic question: why is the constructor needed in class?

Below is a simple test:

  • Circle class with a constructor function
  • Circle2 class without a constructor function.
  • … However, both classes work and an instance can be created.

Going back to the topic, why is the constructor needed in class?

console.log ('//1 ----------- ES6 Classes ----------- ');

class Circle{
    draw(){console.log ('hello');}


c = new Circle(1);

class Circle2{
        this.radius = radius;
    draw(){console.log ('hello');}


c2 = new Circle2(1);

Now, to both your classes, add a circumference method. One that uses the this.radius to dynamically calculate it.

Without a constructor, you do all the same steps as with one, with one thing missing. Here are the steps:

  1. Create a new empty object.
    2 Initialize that object by the blueprint in the constructor.
  2. Connect the new object into the prototype chain, giving it access to methods defined in the class indirectly.

You’re missing step two, so you’ve created an empty object and tied its prototype to the circle prototype… But your new thing itself is completely empty.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.