[英]How to use a decorator to overwrite a static method of a class in typescript
Here is what I do in javascript这是我在 javascript 中所做的
class A {
static foo (a, b, callback) {
setTimeout(() => {
let result = doSomethig(a, b)
callback(result)
}, 1000)
}
}
function decorator (OriginalClass) {
return class extends OriginalClass {
static foo (a, b) {
return new Promise((res) => {
super.foo(a, b, (result) => {
res(result)
})
})
}
}
}
@decorator
class B extends A {
}
let result = await B.foo(10, 20)
I want to overwrite a method of a class, and in the overwritten method, I want to call the original method.我想覆盖一个类的方法,在覆盖的方法中,我想调用原来的方法。 Is there any way to do this in Typescript?有没有办法在打字稿中做到这一点?
You can do something like this:你可以这样做:
class A {
static bar() {
console.log("barA");
}
}
function decorator(OriginalClass: any) {
let baseBar = OriginalClass.bar;
OriginalClass.bar = function () {
baseBar();
console.log("barOverridden");
}
return OriginalClass;
}
@decorator
class B extends A {
}
B.bar();
function StaticMethodDecorator(
target: Function, // the function itself and not the prototype
propertyKey: string | symbol, // The name of the static method
descriptor: TypedPropertyDescriptor<any>
) {
console.log("StaticMethodDecorator called on: ", target, propertyKey, descriptor);
}
class StaticMethodDecoratorExample {
@StaticMethodDecorator
static staticMethod() {
}
}
as described at: https://khru.gitbooks.io/typescript/static_method_decorator.html如以下所述: https : //khru.gitbooks.io/typescript/static_method_decorator.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.