我有一些类似这样的代码:
function changeProperty(prototype: Object,propertyKey: string) {
Object.defineProperty(prototype,'extra',{
get: () => 'added'
});
const existing = Object.getOwnPropertyDescriptor(prototype,propertyKey);
Object.defineProperty(prototype,propertyKey,{
get: () => 'pass'
});
}
class Test {
@changeProperty
get original() { return 'fail'}
}
// Write TypeScript code!
const appDiv: HTMLElement = document.getElementById('app');
const x = new Test() as any;
appDiv.innerHTML = `original: ${x.original}<br/>extra: ${x.extra}`;
https://stackblitz.com/edit/typescript-j8s1bq
我观察到extra
属性已成功添加,但是我无法覆盖/覆盖/删除现有属性。
我不知道为什么会这样。
如果使用类装饰器,则可以使用相同的技术来覆盖getter。