Narutocc / Vue

:smirk_cat:Vue is a progressive framework for building user interfaces. Vue is also perfectly capable of powering sophisticated Single-Page Applications when used in combination with modern tooling and supporting libraries.
1 stars 0 forks source link

ts decorator装饰器 #79

Open Narutocc opened 4 years ago

Narutocc commented 4 years ago

decorator

Decorator是ES7中添加的JavaScript新特性。而typescript早已经支持Decorator的使用。

装饰器是一种特殊类型的声明,它能够被附加到类声明,方法,访问符,属性或参数上。装饰器使用@expression这种形式,expression求值后必须为一个函数,它会在运行时被调用,被装饰的声明信息作为参数参入。

函数装饰器

/**
 * target -> 被装饰的对象
 * key -> 被装饰的函数名
 * descriptor -> 被传递过来的属性的属性描述符,可以通过 Object.getOwnPropertyDescriptor()方法来查看属性描述符
 *
 * target 对于静态成员来说是类的构造函数,对于实例成员来说是类的原型对象
 * propertyKey 成员的名字,这里是method
 * descriptor 成员的属性描述符
 */

在typescript中,当多个装饰器应用在一个声明上时会进行如下步骤的操作:

**1. 由上至下依次对装饰器表达式求值

  1. 求值的结果会被当做函数,由下至上依次调用。**
    <script lang='ts'>
    function f () {
    console.log('f(): evaluated')
    return function (target, propertyKey: string, descriptor: PropertyDescriptor) {
      console.log('f(): called')
    }
    }
    function g () {
    console.log('g(): evaluated')
    return function (target, propertyKey: string, descriptor: PropertyDescriptor) {
      console.log('g(): called')
    }
    }
    class C {
    @f()
    @g()
    method () {}
    }
    // 打印结果如下:
    // f(): evaluated
    // g(): evaluated
    // g(): called
    // f(): called
    </script>