微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

typescript装饰器-属性装饰器

首先我们先创建一个Name类

class Name {
    constructor() { }
    consoleMsg() {
        console.log(22222)
    }
}

然后我们再Greeter类中调用Name类的consoleMsg方法,在不使用继承的情况下我们可能会这么写

class Greeter {
    property = "property";
    hello: string;

    newProperty: Name

    constructor(hello: string) {
        this.hello = hello
        this.newProperty = new Name()
    }

    getMsg() {

        this.newProperty.consoleMsg()
    }
}

自从有了装饰器后,我们可以使用装饰器来美化我们的代码

type Ctor<T> = new (...args: any[]) => T

function auto<T>(className: Ctor<T>) {
    return function (target: any, attr: any) {
      // target 是类的原型对象, attr 属性名称 (url)
        console.log(target);
        console.log(attr);
        console.log(className)
        target[attr] = new className();
    }
}
class Greeter {
    property = "property";
    hello: string;

    @auto(Name)
    newProperty: Name

    constructor(hello: string) {
        this.hello = hello
    }

    getMsg() {

        this.newProperty.consoleMsg()
    }
}
new Greeter('你好').getMsg();

另外我们可以把auto方法单独封装出去,这样我们的代码是不是更简洁来那!

下面我们执行下代码,看下结果:

 

 

 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐