小满nestjs(第三章 前置知识装饰器)

1、什么是装饰器

装饰器是一种特殊的类型声明,他可以附加在类,方法,属性,参数上面

装饰器写法 tips(需要开启一项配置)

类装饰器 主要是通过@符号添加装饰器

他会自动把class的构造函数传入到装饰器的第一个参数 target

然后通过prototype可以自定义添加属性和方法

function decotators (target:any) {
    target.prototype.name = '小满'
}

@decotators

class Xiaoman {

    constructor () {

    }

}

const xiaoman:any = new Xiaoman()

console.log(xiaoman.name)

属性装饰器

同样使用@符号给属性添加装饰器

他会返回两个参数

1.原形对象

2.属性的名称

const currency: PropertyDecorator = (target: any, key: string | symbol) => {
    console.log(target, key)
}


class Xiaoman {
    @currency
    public name: string
    constructor() {
        this.name = ''
    }
    getName() {
        return this.name
    }
}

 参数装饰器

同样使用@符号给属性添加装饰器

他会返回两个参数

1.原形对象

2.方法的名称

3.参数的位置从0开始

const currency: ParameterDecorator = (target: any, key: string | symbol,index:number) => {
    console.log(target, key,index)
}


class Xiaoman {
    public name: string
    constructor() {
        this.name = ''
    }
    getName(name:string,@currency age:number) {
        return this.name
    }
}

方法装饰器 

同样使用@符号给属性添加装饰器

他会返回两个参数

1.原形对象

2.方法的名称

3.属性描述符  可写对应writable,可枚举对应enumerable,可配置对应configurable

const currency: MethodDecorator = (target: any, key: string | symbol,descriptor:any) => {
    console.log(target, key,descriptor)
}


class Xiaoman {
    public name: string
    constructor() {
        this.name = ''
    }
    @currency
    getName(name:string,age:number) {
        return this.name
    }
}

猜你喜欢

转载自blog.csdn.net/qq1195566313/article/details/126209732