装饰器基础(Typescript)

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!
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容