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

128
Visualizações
Why can't I update variables in this JavaScript class?

I'm writing a JavaScript class for an object that will get data via ajax on creation. The object and its retrieved data will then be available for use later on.

The problem is that the variables don't update with new values from the ajax call. They stay at whatever values they were initiated at.

Here's a simplified example of my code:

class Foo {
    constructor() {
        this.bar = 0;
        this.makeAjaxCall();
    }

    makeAjaxCall() {
        jQuery.get(
            // ajax logic
        )
        .done(
            function(response) {
                this.bar = response.bar;
            }
        );
    }
}

var bax = new Foo();
console.log(bax.bar); // outputs 0

I've confirmed that the ajax call occurs, both via the network monitor and by console logging the response variable. It's just that the change of variable value doesn't "stick". This also occurs with code later on, so I don't think the issue is me logging before the ajax call completes.

I suspect this is related to late bindings in JavaScript, but I haven't been able to wrap my head around that. Here's what I tried in that realm (it didn't work):

var bax_unbound = new Foo();
var bax = bax_unbound.bind(Foo);
console.log(bax.bar); // still outputs 0
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