有人可以提供一个简单的例子来演示实现装饰器的正确方法,并描述可能的有效装饰器签名中的参数是什么意思吗?
declare type ClassDecorator = <TFunction extends Function>(target: TFunction) => TFunction | void;
declare type PropertyDecorator = (target: Object, propertyKey: string | symbol) => void;
declare type MethodDecorator = <T>(target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<T>) => TypedPropertyDescriptor<T> | void;
declare type ParameterDecorator = (target: Function, propertyKey: string | symbol, parameterIndex: number) => void;
Run Code Online (Sandbox Code Playgroud)
另外,在实现装饰器时是否应该记住哪些最佳实践注意事项?
当我在TypeScript中使用元数据注释类时,例如创建一个Angular2组件,我可以访问该类中的元数据吗?
import {Component} from 'angular2/core';
@Component({
selector: 'app',
templateUrl: '/app/components/app/app.component.html'
})
export class AppComponent {
// can I access 'templateUrl' from above annotation here?
}
Run Code Online (Sandbox Code Playgroud) 我读过"如何实现打字稿装饰器?" 和多个来源,但我有一些东西,也没有能够与装饰.
class FooBar {
public foo(arg): void {
console.log(this);
this.bar(arg);
}
private bar(arg) : void {
console.log(this, "bar", arg);
}
}
Run Code Online (Sandbox Code Playgroud)
如果我们调用函数foo:
var foobar = new FooBar();
foobar.foo("test");
Run Code Online (Sandbox Code Playgroud)
该对象FooBar由console.log(this);in 登录到控制台中foo
该字符串"FooBar {foo: function, bar: function} bar test"由控制台记录在控制台console.log(this, "bar", arg);中bar.
现在让我们使用装饰器:
function log(target: Function, key: string, value: any) {
return {
value: (...args: any[]) => {
var a = args.map(a => JSON.stringify(a)).join();
var result = value.value.apply(this, …Run Code Online (Sandbox Code Playgroud) 我很困惑何时使用术语注释以及何时使用装饰器?
@Component({
selector: 'tabs',
template: `
`
})
export class Tabs {
}
Run Code Online (Sandbox Code Playgroud)