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

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

问题描述

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

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

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

我已经查看了示例,到目前为止我已经整理好了(伪代码")

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天全站免登陆