我有一个具有以下属性的 typescript 类:
export class apiAccount {
private _balance : apiMoney;
get balance():apiMoney {
return this._balance;
}
set balance(value : apiMoney) {
this._balance = value;
}
private _currency : string;
get currency():string {
return this._currency;
}
set currency(value : string) {
this._currency = value;
}
...
我需要为这个类创建一个空白实例:
let newObj = new apiAccount();
然后检查它是否具有例如“货币”的 setter 。
我认为这正是 getOwnPropertyDescriptor
所做的,但显然我错了:
Object.getOwnPropertyDescriptor(newObj, 'currency')
Object.getOwnPropertyDescriptor(newObj, '_currency')
这些都返回undefined。但是 chrome 似乎可以做到!当我将鼠标悬停在实例上时,它会向我显示属性,并将它们显示为未定义。如何获取这些属性名称的列表,或检查对象中是否存在属性描述符?
最佳答案
“问题”在于 Object.getOwnPropertyDescriptor
- 顾名思义 - 仅返回对象自身属性 的描述符。也就是说:只有直接分配给该对象的属性,不是来自其原型(prototype)链中的某个对象的属性。
在您的示例中,currency
属性是在 apiAccount.prototype
上定义的,而不是在 newObj
上定义的。以下代码片段演示了这一点:
class apiAccount {
private _currency : string;
get currency():string {
return this._currency;
}
set currency(value : string) {
this._currency = value;
}
}
let newObj = new apiAccount();
console.log(Object.getOwnPropertyDescriptor(newObj, 'currency')); // undefined
console.log(Object.getOwnPropertyDescriptor(apiAccount.prototype, 'currency')); // { get, set, ... }
如果你想在一个对象的原型(prototype)链中的任何地方找到一个属性描述符,你需要使用 Object.getPrototypeOf
循环:
function getPropertyDescriptor(obj: any, prop: string) : PropertyDescriptor {
let desc;
do {
desc = Object.getOwnPropertyDescriptor(obj, prop);
} while (!desc && (obj = Object.getPrototypeOf(obj)));
return desc;
}
console.log(getPropertyDescriptor(newObj, 'currency')); // { get, set, ... }
关于javascript - 检查 typescript 类是否有 setter/getter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37643254/