TypeScript class decorator that modifies object instance

后端 未结 2 1665
暖寄归人
暖寄归人 2021-02-08 15:59

I\'m making a plugin for Aurelia and need a class decorator that

  1. adds attributes to the new object instance, and
  2. calls an external function with the new
2条回答
  •  死守一世寂寞
    2021-02-08 16:13

    Why not just assign those properties to the prototype, and subsequently assign to the instance on first invocation

    // decorator
    function addAndCall(cb: Function, newField: string) {
      // cb is now available in the decorator
      return function(ctor: Function): void {
    
        Object.defineProperty(ctor.prototype, newField, {
          value: function(...args: any[]) {
            return Object.defineProperty(this, newField, {
    
              value: function(...args: any[]) {
                console.log(newField, ...args);
              }
    
            })[newField](...args);
          }
        });
        cb(ctor);
      }
    }
    
    let callMe = (decoratedCtor) => console.log(decoratedCtor);
    @addAndCall(callMe, 'propertyName')
    class AddToMe {}
    
    let addToMe = new AddToMe();
    (addToMe).propertyName(1, 2);
    

提交回复
热议问题