zoukankan      html  css  js  c++  java
  • ES6知识点整理之----Decorator(修饰器)

    类的修饰


    修饰器是一个对类进行处理的函数。修饰器函数的第一个参数,就是所要修饰的目标类。
    修饰器的行为:
    @decorator
    class A {}
    
    // 等同于
    
    class A {}
    A = decorator(A) || A;

    @testable:修改了类的行为,为它加上了静态属性isTestable
    @testable
    class MyTestableClass {
      // ...
    }
    
    //target是MyTestableClass类本身
    function testable(target) {
      target.isTestable = true;
    }
    
    MyTestableClass.isTestable // true

    如果觉得一个参数不够用,可以在修饰器外面再封装一层函数。

    function testable(isTestable) {
      return function(target) {
        target.isTestable = isTestable;
      }
    }
    
    @testable(true)
    class MyTestableClass {}
    MyTestableClass.isTestable // true
    
    @testable(false)
    class MyClass {}
    MyClass.isTestable // false

    如果想添加实例属性,可以通过目标类的prototype对象操作。

    function testable(target) {
      target.prototype.isTestable = true;
    }
    
    @testable
    class MyTestableClass {}
    
    let obj = new MyTestableClass();
    obj.isTestable // true

    方法的修饰

    修饰器不仅可以修饰类,还可以修饰类的属性。
    class Person {
      @readonly
      name() { return `${this.first} ${this.last}` }
    }

    修饰器函数readonly一共可以接受三个参数:

    • 第一个参数是类的原型对象
    • 第二个参数是所要修饰的属性名
    • 第三个参数是该属性的描述对象

    @log修饰器,可以起到输出日志的作用。

    class Math {
      @log
      add(a, b) {
        return a + b;
      }
    }
    
    function log(target, name, descriptor) {
      var oldValue = descriptor.value;
    
      descriptor.value = function() {
        console.log(`Calling ${name} with`, arguments);
        return oldValue.apply(this, arguments);
      };
    
      return descriptor;
    }
    
    const math = new Math();
    
    // passed parameters should get logged now
    math.add(2, 4);

    修饰器有注释的作用。

    @testable
    class Person {
      @readonly
      @nonenumerable
      name() { return `${this.first} ${this.last}` }
    }
    
    //Person类是可测试的,而name方法是只读和不可枚举的。
    修饰器只能用于类和类的方法,不能用于函数,因为存在函数提升。

    core-decorators.js(略)

    是一个第三方模块,提供了几个常见的修饰器,通过它可以更好地理解修饰器。

    使用修饰器实现自动发布事件(略)

    Mixin模式(略)

    Trait(略)

    Trait 也是一种修饰器,效果与 Mixin 类似,但是提供更多功能

    Babel 转码器的支持(略)

    目前,Babel 转码器已经支持 Decorator。


































  • 相关阅读:
    类加载机制
    PTA(BasicLevel)-1094 谷歌的招聘
    PTA(BasicLevel)-1023 组个最小数
    异构图神经网络笔记-Heterogeneous Graph Neural Network(KDD19)
    PTA(BasicLevel)-1014 福尔摩斯的约会
    PTA(BasicLevel)-1013 数素数
    PTA(BasicLevel)-1012 数字分类
    PTA(BasicLevel)-1010 一元多项式求导
    PTA(BasicLevel)-1009 说反话
    PTA(BasicLevel)-1008数组元素循环右移问题
  • 原文地址:https://www.cnblogs.com/adhehe/p/9687040.html
Copyright © 2011-2022 走看看