我想在 Typescript 装饰器和reflect-metadata的帮助下创建一个抽象。但是当我调用传递给元数据的函数时,this
它是未定义的:
import "reflect-metadata";
const METHODS = "__methods__";
const Method = (obj: object) => {
return function MethodDecorator(
target: object,
methodName: string | symbol,
descriptor: PropertyDescriptor
) {
const metadata = Reflect.getMetadata(METHODS, obj);
Reflect.defineMetadata(
METHODS,
{ ...metadata, [methodName]: descriptor.value },
obj
);
};
};
const someObject: object = new Object();
class Main {
private num = 42;
constructor(other: Other) {
other.init(someObject);
}
@Method(someObject)
myMethod() {
console.log("hello");
console.log(this.num); // this is undefined (how can I fix it?)
}
}
class Other {
private methods: Record<string, Function> = {};
init(obj: object) {
this.methods = Reflect.getMetadata(METHODS, obj);
}
trigger(methodName: string) {
this.methods[methodName]();
}
}
const other = new Other();
new Main(other);
other.trigger("myMethod");
上面代码片段的输出是
hello
undefined
为什么this
未定义,我该如何解决?
您可以通过克隆此示例 repo 并运行来自己尝试
yarn install
yarn start