装饰器实验

2022-10-23  本文已影响0人  Nick_4438

装饰器实验

说明

ts内包含了四个装饰器,类装饰器、属性装饰器、函数装饰器、参数装饰器,本文中测试一下其的使用。

准备工作

mkdir test
cd test 
touch index.ts

编写代码

类装饰器ClassDecorator

const doc: ClassDecorator =(target: any)=>{
    // 不破坏原有的类给他添加一些属性
    console.log(target)
    target.prototype.name="张三"
}


@doc
class Student{
    constructor(){

    }
}

// doc(Xiaoman)
// const s1:any = new Student()
// console.log(s1.name)

``ts-node .\index.js

属性装饰器PropertyDecorator

const doc: PropertyDecorator =(target: any,key:string|symbol)=>{
    // 这时候target指向对象,key指向属性
    console.log(target,key)
}

class Student{
    @doc
    public name: string
    constructor(){
        this.name='李四'
    }
}

方法装饰器MethodDecorator

const doc: MethodDecorator =(target: any,key:string|symbol,descriptor:any)=>{
    // 这时候target指向对象,key指向函数,descriptor指向对象描述符
    console.log(target,key,descriptor)
}



class Student{
   
    public name: string
    constructor(){
        this.name='李四'
    }
    @doc
    getName(){

    }
}

// doc(Xiaoman)
// const s1:any = new Student()
// console.log(s1.name)

参数装饰器````

const doc: ParameterDecorator =(target: any,key:string|symbol,index:any)=>{
    // 这时候target指向对象,key指向函数,index索引(0开始)
    console.log(target,key,index)
}



class Student{
   
    public name: string
    constructor(){
        this.name='李四'
    }
   
    getName(@doc name:string ,  address: string){

    }
}

// doc(Xiaoman)
// const s1:any = new Student()
// console.log(s1.name)
上一篇下一篇

猜你喜欢

热点阅读