我想用TypeScript装饰器创建一个属性getter和setter,但是当属性被更改或请求时,我不得不定义要运行的函数。
如果我的Field.watch
装饰器有以下用法:
export class Test {
...
@Field.watch({onSet: this.resetCssCache})
public layoutId = 0;
...
public resetCssCache() {
...
}
...
}
而装饰者的实现是:
export class Field {
public static watch(watchers: { onGet?: () => any, onSet?: (newValue: any, oldValue: any) => any }): Function {
return (target: any, key: string) => {
// property getter
const getter = function() {
return this['_' + key];
};
// property setter
const setter = function(newVal) {
if (watchers.onSet) {
this['_' + key] = watchers.onSet(newVal, this['_' + key]);
}
this['_' + key] = newVal;
};
// Delete property.
if (delete this[key]) {
// Create new property with getter and setter
Object.defineProperty(target, key, {
get: getter,
set: setter,
enumerable: true,
configurable: true
});
}
}
}
}
我在@Field.watch({onSet: this.resetCssCache})
上看到一个错误,告诉我this
没有定义。
我想装饰器是在定义级别而不是在实例级别上解释的。是否有方法将非静态方法绑定到我的装饰器的onSet属性?
发布于 2018-04-17 12:37:50
不能通过装饰器内部的this
访问方法,可以使用prototype
传递该方法
export class Test {
@Field.watch({onSet: Test.prototype.resetCssCache })
public layoutId = 0;
public resetCssCache() {
}
}
请注意,这意味着当您调用watchers.onSet(newVal, this['_' + key]);
时,resetCssCache
内部的this
实际上将是watchers
而不是Test
的实例。应该使用call
调用它,这样就可以显式地传递this
watchers.onSet.call(this, newVal, this['_' + key])
。
https://stackoverflow.com/questions/49877756
复制相似问题