我正在为 Aurelia 制作一个插件,需要一个类装饰器
- 向新对象实例添加属性,并且
- 以新对象作为参数调用外部函数。
我已经查看了示例,到目前为止我已经将它们放在一起(“伪代码”)
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 框架有问题)。
如有任何帮助和解释,我们将不胜感激!
最佳答案
为什么不直接将这些属性分配给原型(prototype),然后在第一次调用时分配给实例
// 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);
关于class - 修改对象实例的 TypeScript 类装饰器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41397947/