Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript ES6: How to retrieve calling subclass from a static method defined in superclass

New to JavaScript.

Seeking some guidance on how to access the calling class name from a static method defined in the superclass using ES6 classes. I've spent an hour searching, but have not been able to come up with a solution.

A code snippet may help clarify what I am seeking

class SuperClass {
    get callingInstanceType() { return this.constructor.name }
    static get callingClassType() { return '....help here ...' }
}

class SubClass extends SuperClass { }

let sc = new SubClass()

console.log(sc.callingInstanceType)     // correctly prints 'SubClass'
console.log(SubClass.callingClassType)  // hoping to print 'SubClass'

As illustrated above, I can easily get the subclass name from a instance. Not quite sure how to access from a static method.

Ideas for the implementation of static get callingClassType() welcomed.

like image 658
So Over It Avatar asked May 21 '17 04:05

So Over It


1 Answers

callingClassType is a function (well, a getter in this case, same thing). The value of this inside a function depends on how it is called. If you call a function with foo.bar(), then this inside bar will refer to foo.

Thus if you "call" the function with SubClass.callingClassType, this will refer to SubClass. SubClass is itself a (constructor) function thus you can get its name via the name property.

So your method definition should be

static get callingClassType() { return this.name; }

class SuperClass {
  get callingInstanceType() {
    return this.constructor.name
  }
  static get callingClassType() {
    return this.name
  }
}

class SubClass extends SuperClass {}

let sc = new SubClass()

console.log(sc.callingInstanceType)
console.log(SubClass.callingClassType)

Have a look at the MDN documentation to learn more about this.

like image 128
Felix Kling Avatar answered Sep 19 '22 10:09

Felix Kling