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 beBase
, 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
2 Answers
Reset to default 8The 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
版权声明:本文标题:javascript - Getting the name of a class on which a static function has been called - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744322298a2600560.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论