vic*_*pro 3 decorator typescript
export class UmsDictionary {
public aField = "SUPER";
@PropertyAlias('aField')
public dictionary = "dictionary";
}
export function PropertyAlias(name: string) {
return (target: any, key: string) => {
Object.defineProperty(target, key, {
configurable: false,
get: () => {
return target[name];
},
set: (val) => {}
})
}
}
Run Code Online (Sandbox Code Playgroud)
...
const dct = new UmsDictionary();
console.log("VALUE = " + dct.dictionary); //undefined
Run Code Online (Sandbox Code Playgroud)
我试图通过调用字典属性的 getter 来获取属性 aFiled 的值。我的错误是什么?谢谢
target不会是类的实例,它将是类本身。要访问字段值,您需要this在 get/set 函数内部使用而不是使用箭头函数:
export class UmsDictionary {
public aField = "SUPER";
@PropertyAlias('aField')
public dictionary = "dictionary";
}
export function PropertyAlias(name: string) {
return (target: any, key: string) => {
Object.defineProperty(target, key, {
configurable: false,
get: function (this: { [name: string]: any}) {
return this[name];
},
set: function (this: { [name: string]: any}) {
}
})
}
}
const dct = new UmsDictionary();
console.log("VALUE = " + dct.dictionary); //undefined
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3187 次 |
| 最近记录: |