Skip to content

装饰器的实现原理

核心答案

装饰器的实现其实是使用了 Object.defineProperty, 装饰器方法可以获取到属性描述符,并对其进行修改,修改完成后调用 Object.defineProperty 代理类的原型 一句话:装饰器的三个参数就是 Object.defineProperty 的三个参数

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

function decorate(target, property, descriptor) {
  const oldValue = descriptor.value;
  descriptor.value = (msg) => {
    console.log("装饰器执行");
    return oldValue.apply(null, msg);
  };
}

const anotation = (target, property, decorate) => {
  const descriptor = decorate(
    Log.prototype,
    property,
    Object.getOwnPropertyDescriptor(Log.prototype, property) // 获取属性的描述符
  );

  Object.defineProperty(Log.prototype, property, descriptor);
};

const log = new Log();
log.eat("吃饭");
class Log {
  eat(msg) {
    console.log(msg);
  }
}

function decorate(target, property, descriptor) {
  const oldValue = descriptor.value;
  descriptor.value = (msg) => {
    console.log("装饰器执行");
    return oldValue.apply(null, msg);
  };
}

const anotation = (target, property, decorate) => {
  const descriptor = decorate(
    Log.prototype,
    property,
    Object.getOwnPropertyDescriptor(Log.prototype, property) // 获取属性的描述符
  );

  Object.defineProperty(Log.prototype, property, descriptor);
};

const log = new Log();
log.eat("吃饭");