我有一个打字稿类,它具有以下属性:
I have a typescript class which has the following properties:
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; } ...我需要创建一个这样的空白实例class:
I need to create a blank instance of this class:
let newObj = new apiAccount();然后检查它是否具有货币的设置者。 我认为这正是 getOwnPropertyDescriptor 的确如此,但显然我错了:
And then check if it has the setter for "currency", for example. I thought that this is exactly what getOwnPropertyDescriptor does, however apparently I was wrong:
Object.getOwnPropertyDescriptor(newObj, 'currency') Object.getOwnPropertyDescriptor(newObj, '_currency')这两个都返回undefined。但铬似乎做到了!当我将鼠标悬停在实例上时,它会向我显示属性,并将它们显示为未定义。如何获取这些属性名称的列表,或检查对象中是否存在属性描述符?
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 - 顾名思义 - 只返回对象自己的属性的描述符。即:只有直接分配给该对象的属性,不来自其原型链中某个对象的属性。
The "problem" is that Object.getOwnPropertyDescriptor - as the name implies - only returns descriptors of an object's own properties. That is: only properties that are directly assigned to that object, not those that are from one of the objects in its prototype chain.
In例如,货币属性是在 apiAccount.prototype 上定义的,而不是在 newObj上定义。以下代码段演示了这一点:
In your example, the currency property is defined on apiAccount.prototype, not on newObj. The following code snippet demonstrates this:
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 :
If you want to find a property descriptor anywhere in an object's prototype chain, you'll need to loop with 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, ... }更多推荐
检查typescript类是否有setter / getter
发布评论