Quiero usar this palabra clave en las devoluciones de llamada de $.get(). Mi estructura de código es
var myObject = { get: function() { $.get(server,data,function(data,status) { this.callback(); }); }, callback: function() { } } No quiero usar myObject.callback() . ¿Hay alguna forma de lograrlo usando this.callback() ?
Puede .bind() el valor de this a su función de devolución de llamada antes de pasarlo a $.get() :
var myObject = { get: function() { $.get(server, data, function(data, status) { this.callback(); }.bind(this)); } callback: function { // do something here } } Por supuesto, eso supone que el valor de this dentro de su propia función myObject.get() es correcto, lo cual sería si lo llamara con "notación de puntos" como myObject.get() .
Tenga en cuenta también que si lo único que hace su función anónima es llamar a la otra función, entonces puede vincular la otra función directamente:
var myObject = { get: function() { $.get(server, data, this.callback.bind(this)); } callback: function { // do something here } }Opción n. ° 1: guarde this en una 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 } } Opción n. ° 2: use el método .proxy de jQuery:
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 } }(Editado-- gracias nnnnnn)