[英]Detect static super method in ES6 class
I have one base class and a subclass. 我有一个基类和一个子类。 I want my class types to have a static method that identifies it by a string.
我希望我的类类型具有通过字符串标识它的静态方法。 (So I can do a look up in an object for handlers of a type. I can stick the class in it directly, but converts the entire source of the class to a string and uses that as the key, which seems suboptimal.)
(因此,我可以在对象中查找类型的处理程序。我可以将类直接粘贴在其中,但是可以将类的整个源转换为字符串并将其用作键,这似乎是次优的。)
I need to: 我需要:
super.id()
then append my own id()
super.id()
然后附加我自己的id()
id()
id()
Here is how I'd imagine the code to be written, but super.id
is undefined, so the if
always fails. 这就是我想象的要编写的代码,但是
super.id
是未定义的,因此if
总是失败。 Checking for if (super) {}
also fails as a syntax error and super.id()
fails as it's "not a function". 检查
if (super) {}
还会因为语法错误而失败,而super.id()
因为它不是“函数”而失败。
class Y {
static id() {
if (super.id) {
return `${super.id()}-${this.name}`;
}
else {
return this.name;
}
}
}
class YY extends Y {}
// Outputs "Y YY", but I want "Y Y-YY"
console.log(Y.id(), YY.id())
I could define a static id() {}
method in YY
, but then I'd have to manually do it in all my subclasses which is error prone. 我可以在
YY
定义一个static id() {}
方法,但随后必须在所有容易出错的子类中手动进行此操作。 Is such a thing possible? 这样的事情可能吗?
You can use Object.getPrototypeOf
instead of super
: 您可以使用
Object.getPrototypeOf
代替super
:
class Y { static id() { if (Object.getPrototypeOf(this).id) { return `${Object.getPrototypeOf(this).id()}-${this.name}`; } else { return this.name; } } } class YY extends Y {} console.log(Y.id(), YY.id())
With super
it does not work, since that always refers to the prototype of the Y
class. 对于
super
它不起作用,因为它始终是指Y
类的原型。 But this
matches exactly the object you need the prototype of, so with Object.getPrototypeOf(this).id
you get a nice bubbling-up through the prototype chain. 但是,
this
完全符合你需要的原型对象,因此与Object.getPrototypeOf(this).id
你打通原型链一个不错的起泡了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.