我有一个打字稿类,它具有以下属性:
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();
例如,然后检查它是否具有“货币”的设置器。
我以为这正是getOwnPropertyDescriptor
确实如此,但显然我错了:
Object.getOwnPropertyDescriptor(newObj, 'currency')
Object.getOwnPropertyDescriptor(newObj, '_currency')
These both return undefined. But chrome seems to do it! When I hover over the instance, it shows me the properties, and shows them as undefined. How can I get a list of those property names, or check if the property descriptor exists in the object?
“问题”在于Object.getOwnPropertyDescriptor
- 顾名思义 - 只返回一个描述符对象自身的属性。即:仅直接分配给该对象的属性,not来自其原型链中的对象之一的那些。
在你的例子中,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, ... }
如果您想在对象原型链中的任何位置查找属性描述符,则需要循环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, ... }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)