TypeScript class decorator that modifies object instance

后端 未结 2 1662
暖寄归人
暖寄归人 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();
    (<any>addToMe).propertyName(1, 2);
    
    0 讨论(0)
  • 2021-02-08 16:26

    Here's a working version:

    function addAndCall(target: any) {
        var original = target;
    
        function construct(constructor, args) {
            var c: any = function () {
                this.newAttribute = "object instance value";
                ExternalModule.externalFunction(this);
                return constructor.apply(this, args);;
            }
    
            c.prototype = constructor.prototype;
            return new c();
        }
    
        var f: any = function (...args) {
            return construct(original, args);
        }
    
        f.prototype = original.prototype;
        return f;
    }
    

    (code in playground)

    0 讨论(0)
提交回复
热议问题