修改对象实例的TypeScript类修饰器 [英] TypeScript class decorator that modifies object instance

查看:125
本文介绍了修改对象实例的TypeScript类修饰器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为Aurelia制作一个插件,并且需要一个

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

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

我已经浏览了示例,到目前为止,我已经将它们放在一起(伪ish"代码)

I've looked through examples, and so far I've put together ("pseudo-ish" code)

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;
}

但是

  • 我对这里的细节(或实际需要的内容)不完全清楚,并且
  • 它可能无法正常工作,因为在使用带有此装饰器的类实例化的对象时出现Aurelia错误(并且我怀疑这是我的装饰器,而不是有问题的Aurelia框架).

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

Any help and explanation would be greatly appreciated!

推荐答案

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

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);

这篇关于修改对象实例的TypeScript类修饰器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆