zoukankan      html  css  js  c++  java
  • js-ES6学习笔记-修饰器

    1、修饰器对类的行为的改变,是代码编译时发生的,而不是在运行时。这意味着,修饰器能在编译阶段运行代码。

    2、

    function testable(target) {
      target.isTestable = true;
    }
    
    @testable
    class MyTestableClass {}
    
    console.log(MyTestableClass.isTestable) // true

    上面代码中,@testable就是一个修饰器。它修改了MyTestableClass这个类的行为,为它加上了静态属性isTestable

    3、修饰器不仅可以修饰类,还可以修饰类的属性。

    class Person {
      @readonly
      name() { return `${this.first} ${this.last}` }
    }

    上面代码中,修饰器readonly用来修饰“类”的name方法。

    此时,修饰器函数一共可以接受三个参数,第一个参数是所要修饰的目标对象,第二个参数是所要修饰的属性名,第三个参数是该属性的描述对象。

    function readonly(target, name, descriptor){
      // descriptor对象原来的值如下
      // {
      //   value: specifiedFunction,
      //   enumerable: false,
      //   configurable: true,
      //   writable: true
      // };
      descriptor.writable = false;
      return descriptor;
    }
    
    readonly(Person.prototype, 'name', descriptor);
    // 类似于
    Object.defineProperty(Person.prototype, 'name', descriptor);

    4、修饰器只能用于类和类的方法,不能用于函数,因为存在函数提升。类是不会提升的,所以就没有这方面的问题。

  • 相关阅读:
    ansible常用的一些模块
    使用jmx监控tomcat
    snmp的监控
    Selenium 入门到精通系列:六
    Selenium 入门到精通系列:五
    Selenium 入门到精通系列:四
    Selenium 入门到精通系列:三
    Selenium 入门到精通系列:二
    Selenium 入门到精通系列:一
    Python 发邮件例子
  • 原文地址:https://www.cnblogs.com/zczhangcui/p/6653504.html
Copyright © 2011-2022 走看看