修改对象实例的TypeScript类装饰器

jwx*_*jwx 8 class decorator instances typescript aurelia

我正在为Aurelia制作一个插件,需要一个类装饰器

  1. 将属性添加到新对象实例,和
  2. 使用新对象作为参数调用外部函数.

我已经看了一些例子,到目前为止我已经把它放在了一起("伪ish"代码)

return function addAndCall(target: any): any {
    var original = target;

    var newConstructor = function (...args) {
        original.apply(this, args);
        this.newAttribute = "object instance value";
        ExternalModule.externalFunction(this);
    };

    newConstructor.prototype = Object.create(original.prototype);
    newConstructor.prototype.constructor = original;

    return <any>newConstructor;
}
Run Code Online (Sandbox Code Playgroud)

  • 我不清楚这里的细节(或实际需要的东西),以及
  • 它可能无法正常工作,因为当使用从这个装饰器的类实例化的对象时我得到了Aurelia错误(我怀疑它是我的装饰器而不是Aurelia框架的错误).

任何帮助和解释将不胜感激!

小智 5

为什么不将这些属性分配给原型,然后在第一次调用时分配给实例

// 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);
Run Code Online (Sandbox Code Playgroud)