1. 程式人生 > 其它 >TypeScript裝飾器實現原理

TypeScript裝飾器實現原理

技術標籤:TypeScriptTypeScript裝飾器decorate

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('吃飯')

執行結果如下:
在這裡插入圖片描述

用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('吃飯')

在這裡插入圖片描述