装饰器基础(Typescript)

作者: Dottie22 | 来源:发表于2019-01-21 13:59 被阅读2次
    import "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_test
    console.log(Reflect.getMetadata('field', Test.prototype, 'name')); // value_name
    console.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;
    }
    
    // 自定义 metadatakey
    function 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); // app
    const 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!
    

    相关文章

      网友评论

        本文标题:装饰器基础(Typescript)

        本文链接:https://www.haomeiwen.com/subject/ozrcjqtx.html