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

154
Visualizações
Call back function using `this` in Jquery get()

I want to use this keyword in the callbacks of $.get(). My code structure is

var myObject = {
  get: function() {
    $.get(server,data,function(data,status) {
      this.callback();
    });
  },
  callback: function() {

  }
}

I don't want to use myObject.callback(). Is there any way to accomplish using this.callback()?

about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

You can .bind() the value of this to your callback function before passing it to $.get():

var myObject = {
  get: function() {
    $.get(server, data, function(data, status) {
      this.callback();
    }.bind(this));
  }
  callback: function {
    // do something here
  }
}

Of course, that assumes the value of this within your own myObject.get() function is correct, which it would be if you called it with "dot notation" as myObject.get().

Note also that if the only thing your anonymous function does is call the other function then you can bind the other function directly:

var myObject = {
  get: function() {
    $.get(server, data, this.callback.bind(this));
  }
  callback: function {
    // do something here
  }
}
about 4 years ago · Santiago Trujillo Relatório

0

Option #1 -- cache this in a variable (_this):

var myObject = {
    get: function() {
        var _this = this;
        $.get(server, data, function(data, status) {
            _this.callback(); // this keyword refers to Window obj not myObject
        });
    }
    callback: function {
        // do something here
    }
}    

Option #2 -- use jQuery's .proxy method:

var myObject = {
    get: function() {
        $.get(server, data, $.proxy(function(data, status) {
            _this.callback(); // this keyword refers to Window obj not myObject
        }), this);

    }
    callback: function {
        // do something here
    }
}

(Edited-- thanks nnnnnn)

about 4 years ago · Santiago Trujillo 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