admin管理员组

文章数量:1405170

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.

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.

Share Improve this question edited Apr 8, 2019 at 16:29 Koflin asked Apr 8, 2019 at 15:40 KoflinKoflin 671 silver badge7 bronze badges 4
  • Possible duplicate of Find all classes in a Javascript application that extend a base class – jmargolisvt Commented Apr 8, 2019 at 15:44
  • Wele 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. – Davi Commented Apr 8, 2019 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 Commented Apr 8, 2019 at 15:52
  • @Koflin OK, I get it now. Thanks. I was just wondering :) – Davi Commented Apr 8, 2019 at 15:55
Add a ment  | 

2 Answers 2

Reset to default 8

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.

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());

本文标签: javascriptGetting the name of a class on which a static function has been calledStack Overflow