TS装饰器

一:类的装饰器:是一种与类(class)相关的语法,用来注释或修改类和类方法,装饰器本身是一个函数,装饰器通过@来使用.

//注意装饰器的执行时机,不是在 创建实例的时候运行,而是在类创建的时候就会执行。
function testDec(constructor: any) {
  console.log("123");
}

@testDec
class Person {}
//装饰器对类的行为的改变,是代码编译时发生的,而不是在运行时。这意味着,装饰器能在编译阶段运行代码。也就是说,装饰器本质就是编译时执行的函数。
//所以:这里类Person创建完成即会打印log:123

多个类的装饰器同时使用:

//从上至下(从左至右)收集装饰器,但是执行的时候,先收集的后执行
function testDec(constructor: any) {
  console.log(123);
}

function testDec2(constructor: any) {
  console.log(456);
}

@testDec
@testDec2
class People {}
//456
//123

注意,使用装饰器时,需要修改ts的配置文件


ts中使用装饰器注意修改配置文件这两项.png

当我们需要对装饰器的执行进行控制的时候,即有的时候希望装饰器执行,有的时候不希望他执行,这种时候需要传递参数来进行控制.

function dec(flag: boolean) {
  return function (constructor: any) {
    if (flag) {
     //我们可以对constructor进行拓展
      return constructor.prototype.getName = () =>{
          console.log("dell");
      }
    } else {
      console.log(222);
    }
  };
}

@dec(true)
class Color {
  constructor(private name: string) {}
}
//log输出 111

当我们通过prototype对类进行拓展时存在下面的问题,实例化对象上不找不到拓展的方法(属性)

function testDecorator(constructor: any) {
  constructor.prototype.getName = () => {
    return "lee";
  };
}
@testDecorator
class Test {
  constructor(public name: string) {}
}

const test = new Test("lili");
test.getName();
//可以通过这种方式来解决,但是不符合ts的思想
(test as any).getName();
装饰过的类上找不到拓展的方法.png

未解决上图的问题,我们对代码进行优化,用工厂方法对装饰器进行封装,返回一个装饰过的类

//这里做一层封装,返回一个装饰器
function testDecorator() {
  //泛型,一个可以接收多个参数的构造函数
  return function  any>(constructor: T) {
    return class extends constructor {
      name = "lee";
      getName() {
        return this.name;
      }
    };
  };
}
//获取装饰器装饰过的类
const Test = testDecorator()(
  class {
    constructor(public name: string) {}
  }
);
//此时可以调用getName方法
const test = new Test("lili");
console.log(test.getName());

二:方法的装饰器

//普通函数的target:类的prototype原型
//静态函数的target:类的构造函数
function funcDec(target: any, key: string, descriptor: PropertyDescriptor) {
  console.log(target, key);
  //descriptor.writable = false;//设置是否可修改
  descriptor.value= ()=>{
      return "newName"  
  }
}

class Question {
  name: string;
  constructor(name: string) {
    this.name = name;
  }
  @funcDec
  getName() {
    return this.name;
  }
}
const question = new Question("问题");
console.log(Question.prototype);
question.getName();
descriptor参考js的Object.defineProperty方法.png

语法:Object.defineProperty(obj,property,descriptor)
参数一:obj
绑定属性的目标对象
参数二:property
绑定的属性名
参数三:descriptor
属性描述(配置),且此参数本身为一个对象
属性值1:value
设置属性默认值
属性值2:writable
设置属性是否能够修改
属性值3:enumerable
设置属性是否可以枚举,即是否允许遍历
属性值4:configurable
设置属性是否可以删除或编辑属性值5:get

获取属性的值
属性值6:set
设置属性的值

三:访问器的装饰器

function visitDec(target: any, key: string, descriptor: PropertyDescriptor) {
  //descriptor.configurable = false;
}

class Book {
  private _name: string;
  constructor(name: string) {
    this._name = name;
  }
  @visitDec
  get name() {
    return this._name;
  }

  set name(name: string) {
    this._name = name;
  }
}

const book = new Book("三体");
book.name = "三体2"; //触发set
console.log(book.name); //触发get
注意.png

四.属性的访问器

//属性访问器只能接收两个参数,需要手动的返回descriptor
function nameDec(target: any, key: string): any {
//这里修改的并不是实例上的name,而是原型上的name
  target[key] = "第一行代码";
  const descriptor: PropertyDescriptor = {
    writable: true,
  };
  return descriptor;
}
//类中的属性name是放在实例上的
class Book {
  @nameDec
  name: string;
  constructor(name: string) {
    this.name = name;
  }
}

const book = new Book("三体");
book.name = "三体2";
console.log(book.name);

五:参数上的装饰器

//类的原型 方法名   参数所在的位置
function paramDec(target: any, key: string, paramsIndex: number) {
  console.log(target, key, paramsIndex);
}

class Book {
  getBookName(@paramDec name: string, price: number) {
    return `书名:${name},价格是:${price}`;
  }
}
//Book {} getBookName 0

六.装饰器的简单应用

const BookInfo: any = undefined;

class Book {
  getBookName() {
    try {
      return BookInfo.name;
    } catch (e) {
      console.log("BookInfo -- name 不存在");
    }
  }
  getBookPrice() {
    try {
      return BookInfo.price;
    } catch (e) {
      console.log("BookInfo --- price 不存在");
    }
  }
}

const book = new Book();
book.getBookName(); //BookInfo -- name 不存在
book.getBookPrice(); //BookInfo --- price 不存在

上面的方法能够成功的捕获到错误,但是当存在大量的属性需要try catch时,上面的方式过于复杂,复用性太低.这个时候我们可以用装饰器来进行统一的捕获错误的处理.

//为了给出精确的提示,我们用工厂方法进行封装个
function catchError(msg: string) {
  return function (target: any, key: string, descriptor: PropertyDescriptor) {
    let fn = descriptor.value;
    descriptor.value = () => {
      try {
        fn();
      } catch (e) {
        console.log(msg);
      }
    };
  };
}
const BookInfo: any = undefined;

class Book {
  @catchError("BookInfo -- name 不存在")
  getBookName() {
    return BookInfo.name;
  }
  @catchError("BookInfo -- price 不存在")
  getBookPrice() {
    return BookInfo.price;
  }
}

const book = new Book();
book.getBookName(); //BookInfo -- name 不存在
book.getBookPrice(); //BookInfo --- price 不存在

你可能感兴趣的:(TS装饰器)