【发布时间】:2020-09-15 22:04:34
【问题描述】:
我的所有层次结构中都有一些静态的东西(在这个例子中,_image)。我希望能够访问对应的_image 而无需重复代码:
这会很棒:
class Actor {
static _image; // I need it to be static
method show(){ // I need it to be non-static
this.setImage(this.class._image); //doesn't work....
}
}
class GoodActor extends Actor {
static _image = 'good.png'
}
class BadActor extends Actor {
static _image = 'bad.png'
}
class MediumActor extends Actor {
static _image = 'medium.png'
}
但它不起作用。现在我只需要:
class Actor {
}
class GoodActor extends Actor {
static _image = 'good.png' // I need it to be static
method show(){ // I need it to be non-static
this.setImage(GoodActor._image);
}
}
class BadActor extends Actor {
static _image = 'bad.png' // I need it to be static
method show(){ // I need it to be non-static
this.setImage(BadActor._image);
}
}
class MediumActor extends Actor {
static _image = 'medium.png' // I need it to be static
method show(){ // I need it to be non-static
this.setImage(MediumActor._image);
}
}
假设这四个类有更多的方法。我不想在每个子类中重复 show() 方法...但是我 需要 show() 方法是 非静态 和 @987654328 @ 被静态访问。
我已经阅读了这个问题https://github.com/Microsoft/TypeScript/issues/7673,但不幸的是我不能在那里问,因为他们没有修复它就关闭了它。他们都没有谈到需要动态解析要调用的静态方法的问题。
【问题讨论】:
-
为什么你需要让它保持静态?对可变事物使用静态变量通常会尖叫“有问题”。
-
嗨!是的,我知道这有点奇怪。这是一个网络游戏。我需要在构建演员之前拥有演员的图像,以便能够预加载它们。建议接受:)
-
将图像放置在某种与这些无关的静态对象中并从那里加载它们。
标签: typescript static-methods template-method-pattern