[英]How can I list all the get properties from a give object?
Give the class:给班级:
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; }
}
How can I get the getters properties ie, ["a", "n"]
?我怎样才能获得吸气剂属性,即
["a", "n"]
? I have no code to show yet, I've looked reflect
and reflect-metadata
and I couldn't find anything to list those.我还没有要显示的代码,我查看了
reflect
和reflect-metadata
,但找不到任何可以列出它们的内容。 I'm using typescript but javascript solutions are welcome too.我正在使用打字稿,但也欢迎使用 javascript 解决方案。
You can iterate over the property descriptors of the prototype (or of the object and every one of its prototypes) and see if the descriptor has a get
function.您可以遍历原型(或对象及其每个原型)的属性描述符,并查看描述符是否具有
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);
For Typescript, just annotate with const logGetters = (obj: object) => {
.对于打字稿,只需使用
const logGetters = (obj: object) => {
注释。
You can filter
over Object.getOwnPropertyDescriptors
.您可以
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.