[英]How can I list all the get properties from a give object?
给班级:
export class Foo
{
#x: number;
#y : number;
constructor()
{
this.#x = 20;
this.#y = 10;
}
public get a(): string { return "baa"; }
public get n(): number { return 20; }
}
我怎样才能获得吸气剂属性,即["a", "n"]
? 我还没有要显示的代码,我查看了reflect
和reflect-metadata
,但找不到任何可以列出它们的内容。 我正在使用打字稿,但也欢迎使用 javascript 解决方案。
您可以遍历原型(或对象及其每个原型)的属性描述符,并查看描述符是否具有get
函数。
const logGetters = obj => { if (!obj) return; for (const [key, desc] of Object.entries(Object.getOwnPropertyDescriptors(obj))) { if (desc.get && key !== '__proto__') console.log(key); // exclude Object.prototype getter } logGetters(Object.getPrototypeOf(obj)); }; class Foo { #x; #y; constructor() { this.#x = 20; this.#y = 10; } get a() { return "baa"; } get n() { return 20; } } const f = new Foo(); logGetters(f);
对于打字稿,只需使用const logGetters = (obj: object) => {
注释。
您可以filter
Object.getOwnPropertyDescriptors
。
class Foo { #x; #y; constructor() { this.#x = 20; this.#y = 10; } get a() { return "baa"; } get n() { return 20; } } const res = Object.entries(Object.getOwnPropertyDescriptors(Foo.prototype)) .filter(([k, d])=>typeof d.get === 'function').map(([k])=>k); console.log(res);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.