美文网首页
装饰器实验

装饰器实验

作者: Nick_4438 | 来源:发表于2022-10-23 16:51 被阅读0次

    装饰器实验

    说明

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

    准备工作

    • 需要先安装nodejs
    • 安装ts支持npm i -s -g tsc
    • 安装ts-nodenpm i-s -g ts-node
    • 创建文件夹编写代码测试
    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)
    

    相关文章

      网友评论

          本文标题:装饰器实验

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