typescript装饰器

47 阅读1分钟
  • 装饰器是一个函数,作用于离它最近的类和属性
  • 下面的@addSay1 @addSay2 作用在Person上面

洋葱模型:首先执行外层函数返回一个函数,返回的函数当装饰器作用于下面最近的类.从而形成了洋葱的结构.

// 装饰器  只能修饰类和 属性 用类扩展类中的属性和方法,不能修饰函数, 函数会有变量提升的问题
function addSay2(target: any) {
  console.log(target)// 是Person构造函数
}
function addSay1(target: any) {
  console.log(target)// 是Person构造函数
  let p = new target('张三李四')
  p.print()
}
@addSay2
@addSay1
class Person {
  constructor(public name: string) {
  }
  print() {
    console.log("打印一些文字")
    console.log(this.name)
  }
}
let p1 = new Person('alice')

// 装饰器的洋葱模型
// 输出结构是1 2 3 33 22 11
function printSay1(val: string) {
  console.log(val)
  return function (target: any) {
    console.log(11)
  }
}
function printSay2(val: string) {
  console.log(val)
  return function (target: any) {
    console.log(22)
  }
}
function printSay3(val: string) {
  console.log(val)
  return function (target: any) {
    console.log(33)
  }
}
@printSay1('1')
@printSay2('2')
@printSay3('3')
class Caclat{
  constructor(public type: string) {
    console.log(type)
  }
}