【发布时间】:2021-07-05 04:07:09
【问题描述】:
使用自定义装饰器,我想将一个带有另一个方法的属性注入一个方法。装饰者:
function test() {
return function(target, key, descriptor) {
const originalMethod = descriptor.value;
descriptor.value = function(...args: any[]) {
Object.defineProperty(this, "foo", {
value: () => console.log("foo fired!"),
enumerable: false,
writable: false
});
return originalMethod.apply(this, args);
};
return descriptor;
};
}
用法:
import { Component} from "@angular/core";
@Component({
selector: "my-app",
template: `<button (click)="bar()">Test</button>`,
})
export class AppComponent {
@test()
bar() {
console.log("bar fired!");
const self = this;
(self as any).foo(); // this works!
(this.bar as any).foo(); // this doesn't works!
}
}
在线查看https://stackblitz.com/edit/angular-ivy-dhfasr?file=src%2Fapp%2Fapp.component.ts
我不明白,因为这行得通:
@test()
bar() {
const self = this;
(self as any).foo();
}
但这不起作用(错误:this.bar.foo 不是函数):
@test()
bar() {
(this.bar as any).foo(); // Error: this.bar.foo is not a function
}
我做错了什么?
【问题讨论】:
标签: angular typescript decorator