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

166
Visualizações
Javascript class variable class inaccessible in forEach loop

In my forEach loop, all my class variables become undefined. Any suggestions ?

class MyClass{
    constructor(){
        this.myVar = "Hello"
    }

    iterate(itemList){
        console.log(this.myVar); // working

        for (var i = 0; i < itemList.length; i++) {
            console.log(this.myVar); // also working
        }

        itemList.forEach(function(element){
            console.log(this.myVar); // NOT working
        });
    }
}

instance = new MyClass();
instance.iterate([0,1]);
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

That because the value of "this" in the forEach function = "undefined", you need to get the value of "this" of the object.

Please check this.

class MyClass{
    constructor(){
        this.myVar = "Hello"
    }

    iterate(itemList){
        console.log(this.myVar); // working
        const that = this;
        itemList.forEach(function(element){
            console.log(that.myVar); // NOT working
        });
    }
}

instance = new MyClass();
instance.iterate([0,1]);

Or you can bind the callback function of the forEach with the object's this.

class MyClass{
    constructor(){
        this.myVar = "Hello"
    }

    iterate(itemList){
        console.log(this.myVar); // working
        itemList.forEach(function(element){
            console.log(this.myVar); // NOT working
        }.bind(this));
    }
}

instance = new MyClass();
instance.iterate([0,1]);

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