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

222
Visualizações
Calling functions of a class via apply doesn't initialize the values in the constructor

I have javascript classes in multiple files. I would like to call a function from a given class by only supplying their names as arguments.

class Index{
    constructor(){
        this.Loader("test", "TestFunc");
    }

    Loader(cname, fname){
        const template = require(`./${cname}.js`);
        const object = new template();
        object[fname].apply();
    }
}

new Index();
module.exports = class Test{
    constructor(){
        this.text = "this text should appear";
    }

    TestFunc(){
        console.log(this.text);
    }
}

When the instance of the Test class gets initialized the constructor will run and prepare the value, but when I call TestFunc via the apply function the same values appear undefined and the error "Cannot read property text of undefined" gets thrown. When calling the function normally via object.TestFunc(); no such error is present.

about 4 years ago · Juan Pablo Isaza
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