user13146542
user13146542

Reputation:

How to prevent constructor of an parent class being called while using child class in javascript

If I have two classes in javascript one inheriting other. When the constructor of base class runs, the constructor of parent class is also called.

    class Parent{
        constructor(){
            alert("Parent constructor Called");
        }
    }

    var parent = new Parent();
    
    class Child extends Parent{
        constructor(){
            super();
            alert("Child constructor Called");
        }
    }
   
    var child = new Child();

Results:-

var parent = new Parent();

Output ->

  1. Alert is made -> "Parent constructor Called".

    var child = new Child();

Output ->

  1. Alert is made -> "Parent constructor Called"
  2. Alert is made -> "Child constructor Called"

How do I prevent the constructor of parent class being called when making object of child class. I am facing a problem that, the parent constructor is calling events method of parent class which calls a method with some ajax request inside it. I want to use the same ajax calling method in the base class too, and I call the that method in events method of child class, and that events method calls the method containing ajax request, but since parent the constructor calls those methods for where it is needed, the ajax method is called twice fetching the same data again. Also many variable names in both the classes are same.

Upvotes: 0

Views: 1370

Answers (1)

Ilan Frumer
Ilan Frumer

Reputation: 32377

By design, every inherited class will always first run the parent constructor.

What you need is to change your implementation so that you can override the behavior.

class Parent{
      alert() {
          alert("Parent constructor Called");
      }

      constructor() {
          this.alert();        
      }
  }

  var parent = new Parent();

  class Child extends Parent{
      alert() {
          alert("Child constructor Called");
      }    
  }

  var child = new Child();

Upvotes: -2

Related Questions