我想创建一组我将使用的泛型方法,而不是支持属性的字段。我需要在setter中做一些常规的东西(在Angular 5中调用事件发射器),我不想每次都写它。
我试过这三件事:
arguments.callee.caller
时,我得到:'caller',
'callee', and 'arguments' properties may not be accessed on strict
mode functions or the arguments objects for calls to them
。还有其他建议吗?
以下用法示例。请注意// somehow get calling property name
评论。在这个例子中,我希望有一个返回"myProperty"
字符串的代码。
class ApplicationComponent {
private readonly properties = new Map<string, any>();
protected getProperty<T>(): T {
const propertyName = // somehow get calling property name
return <T>this.properties[propertyName];
}
protected setProperty<T>(value: T): void {
const propertyName = // somehow get calling property name
const oldValue = <T>this.properties[propertyName];
if (oldValue === value) {
return;
}
this.properties[propertyName] = value;
const eventEmitter = this[`${propertyName}Change`];
if (eventEmitter != null && eventEmitter instanceof EventEmitter) {
eventEmitter.emit(value);
}
}
}
class SomeComponent extends ApplicationComponent {
get myProperty(): SomeType {
return this.getProperty();
}
set myProperty(value: SomeType) {
this.setProperty(value);
}
readonly myPropertyChange = new EventEmitter<SomeType>();
}
详细程度有帮助,因为在生产中这种情况下不可能可靠地获取属性名称。如果getProperty
和setProperty
应该影响特定属性,则它们应该接受属性名称作为参数。
这是property decorators的一个很好的用例。装饰器接受类prototype
对象和属性名称。然后它可以将属性描述符设置为它需要的任何内容
function property(proto, key) {
Object.defineProperty(proto, key, {
get() {
return this.properties[key]
},
set(val) { ... }
});
}
class SomeComponent extends ApplicationComponent {
@property
myProperty: SomeType;
}