nag*_*lzs 2 class-method typescript
如何在TypeScript中获取实例的类?这个问题类似于在运行时在TypeScript中获取对象的类名,但我不想获取类名.我想要上课.
我需要这个吗?TypeScript没有类方法,只有静态方法.但它们不是虚拟的.为了将我的心智模型完全转换为Js代码,我需要有虚拟类方法.
我的想法是做这样的事情:
function classOf<T>(o: T) : any {
return o.class; // How to write this???
}
class Foo {
static tryMe() : string {
return "foo";
}
}
class Bar extends Foo {
static tryMe() : string {
return "bar";
}
}
function testPolymorphClassMethod(instance : Foo) {
console.log(classOf(instance).tryMe());
}
testPolymorphClassMethod(new Foo()); // Should print "foo"
testPolymorphClassMethod(new Bar()); // Should print "bar"
Run Code Online (Sandbox Code Playgroud)
只要具体类可用,我就可以直接调用它的静态方法.如果只有一个实例可用,我想调用它的类的静态方法,例如手动虚拟.
问题是我不知道如何编写classOf函数.它可能根本不可能.
我也在尝试这个:
function classOf<T>(o: T) : typeof T {
return typeof o;
}
Run Code Online (Sandbox Code Playgroud)
但它给出了一个comiple错误:
"T仅指类型,但在此处用作值".
我知道函数是JavaScript(以及TypeScript)中的第一类对象.但TypeScript类可能不是,然后也许不可能做我想要的.
是否有一个解决方法,不需要为每个后代类键入大量代码?
我能得到的最接近的是:
class Virtualizer {
virtual(methodName: string) : any {
return eval(this.constructor.name+"."+methodName);
}
}
class Foo extends Virtualizer {
static getMyName() : string {
return "foo";
}
public test() : string {
return this.virtual("getMyName")();
}
}
class Bar extends Foo {
static getMyName() : string {
return "bar";
}
}
let foo = new Foo();
let bar = new Bar();
console.log(foo.test()); // Prints "foo"
console.log(bar.test()); // Prints "bar"
Run Code Online (Sandbox Code Playgroud)
但这会丢失所有类型的信息,它需要一个共同的基类(或代码重复),我永远不能调用我想调用的实际方法,只是一个"虚拟器".它太笨拙了.
我可以将类相关信息提取到封装的单例对象中,但这需要我将许多方法的可见性从protected更改为public.(并且还在主要和封装对象之间生成大量交叉引用,也非常笨拙.)
你可以归还constructor你的财产o
function classOf<T>(o: T): any {
return o.constructor;
}
Run Code Online (Sandbox Code Playgroud)
见演示
| 归档时间: |
|
| 查看次数: |
1904 次 |
| 最近记录: |