Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

153
Views
Función de devolución de llamada usando `this` en Jquery get()

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

about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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

0

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)

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!