美文网首页
TypeScript装饰器如何实现的?作用是什么?

TypeScript装饰器如何实现的?作用是什么?

作者: 伐樱大魔 | 来源:发表于2020-02-21 17:06 被阅读0次

    TypeScript的作用是什么,应用场景是什么?

    在nest.js中,引入了@controller的概念,里面的@get/@post等装饰器则用来监听url的变化(与java的spring类似),进而作出各自的操作。

    举个例子!

    1. get请求:localhost:3000/users
    // 当前在users这个controller下
    
    @Get()
    getUsers(){
        const users = this.userService.getUsers();
        console.log(users);
    }
    
    1. post请求:localhost:3000/users/add
    {
        name:'zhangshan',
        address:'chengdu'
    }
    
    // 当前在users这个controller下
    
    @Post('add')
    addUser(@Body() body){
        const user = body;
        console.log(user);
    }
    

    这里面的@Get/@Post就是TypeScript里面的装饰器。

    那么,在TypeScript里面,装饰器是如何实现的呢?

    根据上面的案例,暂时知道装饰器可以加在类上,方法上,参数上。

    比如,我们要实现一个装饰器,它的作用是 :
    console.log('Hello' + 类/方法/参数的名称 + 传入的参数的值)

    1. 实现装饰器
    function ClassLogger(params: string){
        return function (target: any) {
            console.log('hello');
            console.log('目标类:',target);
            console.log('接受到的参数:',params);
        }
    }
    
    function PropertyLogger(params: string) {
        return function (target: any, attr: string) {
            console.log('hello');
            console.log('目标属性:',attr);
            console.log('接受到的参数:',params);
        }
    }
    
    function MethodLogger(params: string) {
        return function (target: any, methodName: string) {
            console.log('hello');
            console.log('目标方法:',methodName);
            console.log('接受到的参数:',params);
        }
    }
    
    1. 运用装饰器
    @ClassLogger('chengdu--class')
    class User{
        @PropertyLogger('chengdu--property')
        name: string;
        age: number;
    
        constructor(name: string, age: number){
            this.name = name;
            this.age = age;
        }
    
        @MethodLogger('chengdu--method')
        getName(){
            return this.name;
        }
    }
    const user = new User('zhangshan', 22);
    ![](https://user-gold-cdn.xitu.io/2020/2/1/170006103dda5df1?w=1356&h=772&f=png&s=748306)
    
    1. 看看效果
    image

    这里罗列了一个最简单的实现,对装饰器的实现有了一个大致的思路。装饰器具体的详细的好玩的,后续分享啦!

    相关文章

      网友评论

          本文标题:TypeScript装饰器如何实现的?作用是什么?

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