TypeScript装饰器实现原理

TypeScript注解风格的装饰器

@decorate装饰器函数的作用是在调用eat方法之前执行执行自定义的功能

function decorate(target, property, descriptor) {  
  var oldValue = descriptor.value
  descriptor.value = msg => {
    console.log('先洗手')
    msg = `后 ${msg}`
    return oldValue.apply(null, [msg])
  }
  return descriptor
}

class Log {
  @decorate
  eat(msg) {
      console.log(msg)
  }
}

const log = new Log()
log.eat('吃饭')

运行结果如下:
TypeScript装饰器实现原理_第1张图片

用js实现以上@decorate装饰器

class Log {
  eat(msg) {
      console.log(msg)
  }
}

const decorate = (target, property) => {
  var old = target.prototype.eat
  target.prototype[property] = msg => {
      console.log('先洗手 2')
      msg = `后 ${msg} 2`
      old(msg)
  }
}

decorate(Log, 'eat')  //相当于 eat 上面的 @decorate

const log = new Log()
log.eat('吃饭')

运行结果如下:
在这里插入图片描述

TypeScript装饰器的底层实现原理如下

class Log {
  eat(msg) {
      console.log(msg)
  }
}

function decorate(target, property, descriptor) {  
  var oldValue = descriptor.value
  descriptor.value = msg => {
    console.log('先洗手 3')
    msg = `后 ${msg} 3`
    return oldValue.apply(null, [msg])
  }
  return descriptor
}

const anotation = (target, proterty, decorate) => {
  const descriptor = decorate(
    Log.prototype,
    proterty,
    Object.getOwnPropertyDescriptor(Log.prototype, proterty)
  )
  Object.defineProperty(Log.prototype, proterty, descriptor)
}
anotation(Log, 'eat', decorate)  //相当于 eat 上面的 @decorate


const log = new Log()
log.eat('吃饭')

在这里插入图片描述

你可能感兴趣的:(TypeScript,TypeScript,装饰器,decorate)