Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

160
Vistas
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()?

over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

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
  }
}
over 4 years ago · Santiago Trujillo Denunciar

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)

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda