美文网首页
第十九节: TypeScript装饰器(Decorator)

第十九节: TypeScript装饰器(Decorator)

作者: 时光如剑 | 来源:发表于2022-12-21 19:05 被阅读0次

    装饰器(Decorator)

    装饰器是一种特殊类型的声明,它能够附加到类声明、方法、访问符、属性、类方法的参数上,以达到扩展类的行为。

    自从 ES2015 引入 class,当我们需要在多个不同的类之间共享或者扩展一些方法或行为的时候,代码会变得错综复杂,极其不优雅,这也是装饰器被提出的一个很重要的原因。

    1. 装饰器的了解

    常见的装饰器有:类装饰器、属性装饰器、方法装饰器、参数装饰器。

    装饰器的写法:普通装饰器(无法传参)、 装饰器工厂(可传参)。

    注意: 装饰器是一项实验性功能, 可能会在未来的版本中发生变化

    若要启用实验性的装饰器特性,你必须在命令行或 tsconfig.json 里启用 experimentalDecorators 编译器选项:

    # 命令行
    tsc --target ES5 --experimentalDescorators
    
    // tsconfig.json
    {
        "compilerOptions": {
            "target": "ES5",
            "experimentalDecorators": true
        }
    }
    

    2. 装饰器的使用方法

    装饰器允许你在类和方法定义的时候去注释或者修改它。装饰器是一个函数,它接收三个参数 targetnamedescriptor 然后可选性的返回被装饰之后的 descriptor 对象。

    装饰器使用 @expression 这种语法糖形式,expression 表达式求值后必须为一个函数,它会在运行时被调用,被装饰的声明信息做为参数传入。

    2.1 装饰器工厂

    装饰器工厂就是一个简单的函数,它返回一个装饰器函数,以供装饰器在运行时调用。

    通过装饰器工厂方法,可以额外传参,普通装饰器无法传参。

    装饰器工厂函数的语法:

    function color(val:string){
      // 装饰器工厂
      return function(target){
        // 装饰器
      }
    }
    

    示例:

    // 装饰器工厂函数
    function log(param:string){
        // 返回装饰器函数
      return function (target:any, name:string, descriptor:PropertyDescriptor){
        console.log('param', param)
        //  param with param
        console.log('target', target)
        // target {sayHello: ƒ, constructor: ƒ}
        console.log('name', name)
        // name sayHello
        console.log('descriptor',descriptor)
        // descriptor {writable: true, enumerable: true, configurable: true, value: ƒ}
      }
    }
    
    // 类
    class Person{
      @log('with param')
      sayHello(){
        console.log('hello world')
        // hello world
      }
    }
    
    // 实例化
    const student = new Person()
    student.sayHello()
    

    代码中声明的log()函数就是一个装饰器工厂函数, 装饰器工厂函数的调用,可以接受参数,并返回装饰器函数,在方法运行时调用.

    查看代码的打印结果

    /*
        param with param
        target {sayHello: ƒ, constructor: ƒ}
        name sayHello
        descriptor {writable: true, enumerable: true, configurable: true, value: ƒ}
        
        hello world
    */ 
    

    可以看到,先执行装饰器函数,然后执行 sayHello() 方法。至于类属性装饰器函数表达式的三个参数 targetnamedescriptor 之后会单独介绍。

    2.2 装饰器组成

    可以将多个装饰器应用于声明上,

    多个装饰器写在一行

    @f  @g  x
    

    在多行上使用

    @f
    @g
    x
    

    当多个装饰器应用于单个声明时, 他们的评估类似于数组中函数组合, 在这个模型中, 当组合函数 fg时, 得到的复合(f & g) (x)等价于f(g(x))

    因此, 在TypeScript中对单个声明评估多个装饰器时执行以下步骤

    1. 每个装饰器的表达式都是从上到下计算
    2. 然后将结果作为函数从下到上调用

    通过示例观察调用顺序:

    // 第一个装饰器工厂函数
    function first(){
      console.log('first factory')
    
        // 返回装饰器
      return function (target:any, propertyKey: string, descriptor: PropertyDescriptor){
        console.log('first() called')
      }
    }
    
    
    // 第二个装饰器工厂函数
    function second(){
      console.log('second factory')
    
       // 返回装饰器
      return function (target:any, propertyKey: string, descriptor: PropertyDescriptor){
        console.log('second() called')
      }
    }
    
    
    class ExampleClass{
      @first()
      @second()
      method(){}
    }
    
    /*
     输出的结果
      first factory
      second factory
      second() called
      first() called
    */
    

    示例中通过打印发现, 先自上而下调用装饰器工厂函数,在自下而上调用装饰器

    3. 类装饰器

    类装饰器是在类声明之前声明的, 类的装饰器用于类的构造函数, 可以观察,修改,替换类定义,

    类装饰器表达式在运行时作为函数调用, 装饰类的构造函数作为其唯一参数

    如果类的装饰器返回一个值, 它将用提供的构造函数替换类声明

    注意: 如果你选择返回一个新的构造函数, 你必须注意维护原始原型, 在运行时应用装饰器的逻辑不会为你执行操作

    3.1 类装饰器使用

    例如:

    // 装饰器
    function sealed(constructor:Function){
      console.log('constructor', constructor)
      // 通过seal 方法封闭构造函数和原型对象
      Object.seal(constructor)
      Object.seal(constructor.prototype)
    }
    
    // 装饰类
    @sealed
    class BugReport{
      type= 'report';
      title: string;
    
      constructor(t: string){
        this.title = t
      }
    }
    

    执行时@sealed,它将密封构造函数及其原型,因此将防止在运行时通过访问BugReport.prototype或定义BugReport自身属性来向此类添加或删除任何功能

    这个装饰器不会阻止类的子类化BugReport

    3.2 通过类装饰器扩展类的属性和方法:

    例如:

    // 装饰器
    function personClassDecorator<T extends {new (...args:any[]):{}}>(constructor: T){
    
      return class extends constructor{
        // 扩展类的属性
        hobby = '读书'
    
        // 方法重载
        sayHello(){
          console.log('重载, sayHello')
        }
      }
    }
    
    // 装饰类
    @personClassDecorator
    class Person {
      // 属性
      name :string;
      age = 18;
    
      constructor(name:string){
        this.name = name
      }
    
      // 方法
      sayHello(){
        console.log('Person sayHello')
      }
    }
    
    // 实例化
    const student = new Person('jack')
    console.log(student.name)
    // jack
    console.log(student.age)
    // 18
    console.log(student.hobby)
    // ts报错类型: 类型“Person”上不存在属性“hobby”。。
    // 但编译后依然打印结果:读书
    
    console.log(student)
    /*
    class_1 {
      age: 18
      hobby: "读书"
      name: "jack"
    }
    */
    
    // 调用sayHello 只会答应重载的方法
    student.sayHello()
    // 重载, sayHello
    

    函数表达式写法

    // 装饰器
    function personClassDecorator<T extends {new (...args:any[]):{}}>(constructor: T){
    
      // 表达式的写法
      constructor.prototype.hobby = '读书'
      constructor.prototype.sayHello = () =>{
         console.log('重载, sayHello')
      }
    }
    
    // 装饰类
    @personClassDecorator
    class Person {
      // 属性
      name :string;
      age = 18;
    
      constructor(name:string){
        this.name = name
      }
    
      // 方法
      sayHello(){
        console.log('Person sayHello')
      }
    }
    
    // 实例化
    const student = new Person('jack')
    console.log(student.name)
    // jack
    console.log(student.age)
    // 18
    console.log(student.hobby)
    // ts报错类型: 类型“Person”上不存在属性“hobby”。。
    // 但编译后依然打印结果:读书
    
    console.log(student)
    /*
    class_1 {
      age: 18
      hobby: "读书"
      name: "jack"
    }
    */
    
    // 调用sayHello 只会答应重载的方法
    student.sayHello()
    // 重载, sayHello
    
    

    以上两种写法,其实本质是相同的,类装饰器函数表达式将构造函数作为唯一的参数,主要用于扩展类的属性和方法。

    唯一的区别:

    1. 第一种写法hobby属性存在于实例化对象上
    2. 第二种写法hobby属性存在于原型对象上

    4. 属性装饰器

    属性装饰器是在属性声明之前声明的,属性装饰器的表达式将在运行时作为函数调用,

    并带有以下两个参数:

    1. target: 静态成员的类构造函数, 或实例成员的类的原型
    2. name: 成员名称

    例如:

    // 属性装饰器
    function attrDecorator (target:any,name:string){
        console.log('属性装饰器')
        console.log('target',target)
        // 原型对象: target {sayHello: ƒ, constructor: ƒ}
        console.log('name',name)
        // 属性名称: name name
    }
    
    // 类
    class Person {
        // 属性装饰器
        @attrDecorator
        name: string
    }
    

    5. 方法)装饰器

    方法装饰器在方法声明之前声明, 作用于类属性的装饰器函数表达式会在运行时调用

    方法装饰器的函数表达式将在运行时调用, 并带有以下三个参数

    1. target: 静态成员的类的构造函数, 或者实例成员的类的原型
    2. name: 成员的名称
    3. descriptor: 成员的属性描述符

    如果你熟悉 Object.defineProperty,你会立刻发现这正是 Object.defineProperty的三个参数。

    如果方法装饰器返回一个值, 它将用作该方法的属性描述符

    示例: 将方法类型修改为不可枚举

    // 装饰器
    function enumerable(value:boolean){
      console.log('value',value)
      return function (target: any, propertyKey: string, descriptor: PropertyDescriptor){
        console.log('target', target, propertyKey, descriptor)
          // taget :构造函数 Greeter
          // propertyKey : 装饰方法名称
          // descriptor: 方法的描述对象
        descriptor.enumerable = value
      }
    }
    
    // 类
    class Greeter{
      greeting: string
    
      constructor(message: string){
        this.greeting = message
      }
    
      @enumerable(false)
      greet(){
        return `Hello, ${this.greeting}`
      }
    }
    

    这里装饰器@enumerable(false)是一个装饰器工厂函数, 返回装饰器函数,当调用装饰器函数,它会修改enumerable属性描述符的属性

    6. 方法参数装饰器

    参数装饰器表达式会在运行时当作函数被调用,以使用参数装饰器为类的原型上附加一些元数据,传入下列3个参数 targetnameindex

    1. target: 对于静态成员来说是类的构造函数, 对于实例成员来说是类的原型对象
    2. name: 成员的名字
    3. index: 参数在函数参数列表中的索引

    例如:

    // 方法参数装饰器
    function personParam(target: any, name:string, index:number){
      console.log('target', target)
      // 实例对象的原型target   {sayHello: ƒ, constructor: ƒ}
      console.log('name',name)
      // 参数名称  name sayHello
      console.log('index', index)
      // 参数索引 index 0
    
    }
    
    // 类
    class Person {
    
      // 方法(参数中使用装饰器)
      sayHello(@personParam name: string){
        console.log('hello ' + name)
      }
    }
    
    // 实例化
    const student = new Person()
    
    // 调用sayHello 
    student.sayHello('张三')
    // hello 张三
    

    7. 装饰器的执行顺序

    类装饰器, 属性装饰器,方法装饰器, 参数装饰器的调用顺序

    例如:

    // 类装饰器
    function classDecorator (){
      console.log('类装饰器')
    }
    
    // 属性装饰器
    function attrDecorator (){
      console.log('属性装饰器')
    }
    
    // 方法装饰器
    function methodsDecorator (){
      console.log('方法装饰器')
    }
    
    // 参数装饰器
    function argumentDecorator (target:any, name:string ,index: number){
      console.log('参数装饰器', index)
    }
    
    
    // 类装饰器
    @classDecorator
    class Person {
      // 属性装饰器
      @attrDecorator
      name: string
    
      // 方法装饰器(参数装饰器)
      @methodsDecorator
      sayHello(@argumentDecorator name:string , @argumentDecorator age:number){
        console.log('name', name, age)
      }
    
    }
    
    /*
     装饰器执行顺序:
          属性装饰器
          参数装饰器 1
          参数装饰器 0
          方法装饰器
          类装饰器
    */
    
    

    相关文章

      网友评论

          本文标题:第十九节: TypeScript装饰器(Decorator)

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