JavaScript在defineProperty中使用原始的getter/setter

我想创建一个TypeScript装饰器,它可以扩展属性的getter/setter的逻辑。我尝试将原始属性复制到符号下,并在重新定义该属性时调用该符号。问题是它变成了一个无限循环。

  //Find the latest version of 'attribute' getter setter in the prototype chain
  let obj = _object;
  while(obj && !(Object.getOwnPropertyDescriptor(obj, 'attribute'))){
    obj = Object.getPrototypeOf(obj);
  }

  //Copy original 'attribute' logic under a symbol
  const attributeDesc = Object.getOwnPropertyDescriptor(obj, 'attribute');
  let id=Symbol('__attribute');
  Object.defineProperty(obj, id, attributeDesc);

  //Redefine 'attribute' logic
  Object.defineProperty(_object, 'attribute', {
    get: () => {
      //call original
      const attribute = obj[id]; //It crashes the page (probably infinite loop)

      //extend original logic
      attribute['extend'] = 'property';

      return attribute;
    },
    enumerable: false,
    configurable: true
  });

如果你能给我解释一下为什么会变成这样,那会对我有帮助。我认为新的getter函数引用与原始函数没有任何关系。请给我一个在JavaScript中实现这一点的解决方案。

感谢您的时间和回答!

转载请注明出处:http://www.jndeho.com/article/20230526/1352274.html