装饰器基础 发表于 2019-01-21 装饰器基础- typescript 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970import "reflect-metadata";// 基础@Reflect.metadata("class", "value_test")class Test { @Reflect.metadata("field", "value_name") name = "dottie"; @Reflect.metadata('method', "value_hi") hi(): string { return 'hi, today!' }}console.log(Reflect.getMetadata('class', Test)); // value_testconsole.log(Reflect.getMetadata('field', Test.prototype, 'name')); // value_nameconsole.log(Reflect.getMetadata('method', Test.prototype, "hi")); // value_hi// 获取类型信息,返回值,参数等信息function PropDeco(): PropertyDecorator { return (target: any, key: any) => { console.log(target); // SomeClass {} const type = Reflect.getMetadata("design:type", target, key); console.log(type.name); // String }}class SomeClass { @PropDeco() public name!: string;}// 自定义 metadatakeyfunction Component(value?: string): ClassDecorator { return (target: any) => { Reflect.defineMetadata("component", value, target); }}function Resource(value?: string): PropertyDecorator { return (target: any, key: any) => { Reflect.defineMetadata("field", value, target, key); }}function Method(): MethodDecorator { return (target: any, key: any, descriptor: any) => { Reflect.defineMetadata('method', descriptor.value, target, key); }}@Component("app")class TestClass { @Resource("这是姓名") public name!: string; @Method() public hi():String { return "hi!"; }}const cValue = Reflect.getMetadata('component', TestClass);console.log(cValue); // appconst fValue = Reflect.getMetadata('field', TestClass.prototype, 'name');console.log(fValue); // 这是姓名const mValue = Reflect.getMetadata('method', TestClass.prototype, "hi");console.log(mValue); // [Function]console.log(mValue.call(null)) // hi!