5

So my question is as follows: Can I get the name of a class on which a function got called? To illustrate that problem I will give a short code example.

class Base {
    static getClassName() {
        // get the caller class here
    }
}

class Extended extends Base { }

Base.getClassName(); // Base
Extended.getClassName(); // Extended

Can anyone tell me how to do this, or say if this is even possible.

Koflin
  • 67
  • 1
  • 7
  • Possible duplicate of [Find all classes in a Javascript application that extend a base class](https://stackoverflow.com/questions/31618212/find-all-classes-in-a-javascript-application-that-extend-a-base-class) – jmargolisvt Apr 08 '19 at 15:44
  • Welcome to SO! Sorry, but it doesn't make much sense, does it? When you write `Base.getClassName()` you already know it should be `Base`, right? In other words, the moment you write your code you already know the name of the class because otherwise you wouldn't be able to write the line. – David Apr 08 '19 at 15:49
  • @David you are absolutely right, but passing the name of a class to the function is just annoying if I do it 100 times and I thought it could be easier – Koflin Apr 08 '19 at 15:52
  • @Koflin OK, I get it now. Thanks. I was just wondering :) – David Apr 08 '19 at 15:55

2 Answers2

6

The following code should work:

class Base {
  static getClassName() {
    return this.name;
  }
}

class Extended extends Base {}

console.log(Base.getClassName()); // Base
console.log(Extended.getClassName()); // Extended

In a static method, this refers to the class object itself.

Ulysse BN
  • 10,116
  • 7
  • 54
  • 82
Guillaume Nury
  • 373
  • 3
  • 7
  • `Base.name` works also, and is way simpler. I'd rather use `getClassName` for a non-static method of obtaining the class of an instance at runtime. – Nino Filiu Apr 08 '19 at 15:53
1

In ES6, functions have a read-only name field (doc). Since classes are functions, you can simply use MyClass.name to statically get the class name.

To get the class name of functions at runtime, reference the Function.name of the constructor function.

class Base {
  getClassName() {
    return this.constructor.name;
  }
}
class Extended extends Base {}
console.log(Base.name);
console.log(Extended.name);

const base = new Base();
console.log(base.getClassName());
const extended = new Extended();
console.log(extended.getClassName());
Nino Filiu
  • 16,660
  • 11
  • 54
  • 84