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

161
Views
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 answers
Answer question

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 Report

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 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!