跳至主要內容

装饰器

刘春龙原创...大约 1 分钟WEB前端TypeScript教程文档

6.16 装饰器

装饰器就是一个方法,可以注入到一个类或方法甚至是属性和参数上来扩展他们的功能,使用装饰器不会破坏原有的结构

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

提示

由于装饰器目前处于实验阶段,必须在tsconfig.json配置文件中进行配置才可使用

"compilerOptions": {
    "experimentalDecorators": true,
}

类装饰器(无法参数)

// 装饰器
const fun1: ClassDecorator = (target: any) => {
  console.log(target); // [class Person1]
  target.prototype.name = "lcl";
  target.age = 20;
};
@fun1 // 这里等同于第十一行
class Person1 {}
// fun1(Person1)
const p1 = new Person1();
// @ts-ignore   // 跳过类型检查
console.log(p1.name);
// @ts-ignore
console.log(Person1.age);

装饰器工厂(可传参)

const fun5 = (options: any) => {
  return (target: any) => {
    target.prototype.userName = options.name;
    target.age = options.age;
  };
};
@fun5({
  name: "李四",
  age: 18,
})
class Person5 {}
const p5 = new Person5();
// @ts-ignore   // 跳过类型检查
console.log(p5.userName);
// @ts-ignore
console.log(Person5.age);

装饰器组合

function demo1(target: any) {
  console.log("demo1");
}
function demo2() {
  console.log("demo2");
  return (target: any) => {
    console.log("demo2里面");
  };
}
function demo3() {
  console.log("demo3");
  return (target: any) => {
    console.log("demo3里面");
  };
}
function demo4(target: any) {
  console.log("demo4");
}

@demo1
@demo2()
@demo3()
@demo4
class Person {}

/*结果是:
demo2
demo3
demo4
demo3里面
demo2里面
demo1
*/

属性装饰器

const fun2: PropertyDecorator = (target: Object, key: string | symbol) => {
  console.log(target); // {}
  console.log(key); // name
};

class Person1 {
  @fun2
  public name: string;
  constructor(name: string) {
    this.name = name;
  }
}

参数装饰器

const fun4: ParameterDecorator = (
  target: Object,
  key: string | symbol | undefined,
  index: number
) => {
  console.log(target); // {}
  console.log(key); // sayHi
  console.log(index); // 1
};
class Person1 {
  public name: string;
  constructor(name: string) {
    this.name = name;
  }
  sayHi(name: string, @fun4 age: string) {}
}

方法装饰器

// 装饰器
const fun3: MethodDecorator = (
  target: Object,
  key: string | symbol,
  descriptor: any
) => {
  console.log(target); // {}
  console.log(key); // sayHi
  console.log(descriptor); // { value: [Function: sayHi], writable: true,enumerable: false,configurable: true}
};
class Person1 {
  public name: string;
  constructor(name: string) {
    this.name = name;
  }
  @fun3
  sayHi() {}
}
上次编辑于:
贡献者: 刘春龙
评论
  • 按正序
  • 按倒序
  • 按热度
Powered by Waline v2.15.7