Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

110
Visualizações
Javascript make object string keys enumerable

I have a class set up with string keys, like this:

class MyClass {
    constructor() {
        this.id = 0
        this.data = []
    }

    "GET /data"(req, res) {
        res.json(this.data)
    }
}

The goal is to dynamically loop over the functions in an instance like this:

for (let key in new MyClass()) {
    console.log(key)
}

However, everything I have tried has only resulted in the keys id and data.

I can manually get the function and run it just fine:

let item = new MyClass()
item["GET /data"]()

But it does not show up in any dynamic enumeration I have tried.

Manually setting the enumeration also works:

class MyClass {
    constructor() {
        this.id = 0
        this.data = []
        
        // Here!!!
        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"]

But that defeats the purpose of doing it dynamically. Is there any way to either dynamically get the names of functions with string keys, or make every property enumerable?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

There are two ways to do this

Object.keys(myObj)

or

for (let key in myObj) {
}
about 4 years ago · Juan Pablo Isaza Relatório

0

Object.getOwnPropertyNames(MyClass.prototype)

gives you

["constructor", "GET /data"]
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda