Within my setup, I have a class that contains string keys as follows:
class MyClass {
constructor() {
this.id = 0
this.data = []
}
"GET /data"(req, res) {
res.json(this.data)
}
}
The main objective is to iterate dynamically through the functions within an instance like so:
for (let key in new MyClass()) {
console.log(key)
}
Despite various attempts, all efforts have only revealed the keys `id` and `data`.
I am able to manually retrieve and execute the function successfully:
let item = new MyClass()
item["GET /data"]()
However, it does not appear in any dynamic listing method I have experimented with.
Setting the enumeration manually also proves effective:
class MyClass {
constructor() {
this.id = 0
this.data = []
// Attention!!!
Object.defineProperty(this, "GET /data", {
value: this["GET /data"],
writable: false,
enumerable: true,
configurable: true
})
}
"GET /data"(req, res) {
res.json(this.data)
}
}
console.log(Object.keys(new MyClass())) // ["id", "data", "GET /data"]
Yet, this approach contradicts the fundamental purpose of achieving dynamism. Is there a way to dynamically fetch function names associated with string keys or make every property enumerable?