Michael K. Michael K. - 22 days ago 6
Javascript Question

Determine if super() is called from inherited class

Is there a way to determine that the inheriting class has bothered to call

super()
in JavaScript?

function A() {

A.prototype.isInitialized = function() {
// what can be checked to see if B bothered to called super()
}
}

class B extends A {
//constructor() {
// didn't call super()
//}
}


Assume B didn't have its own constructor. Does it just use A's constructor thus effectively having called super by default?

Answer

Yes, no constructor is the same as a constructor that just calls super, so you don't have to worry about having an uninitialized parent.

class A {
  constructor() {
    this.isInit = true
  }

   isInitialized() {
     return !!this.isInit
   }
}

class B extends A {
  constructor() {
    super()
  }
}

class C extends A {
}


b = new B()
console.log(b.isInitialized())

c = new C()
console.log(c.isInitialized())

Comments