Search code examples
javascriptthisjquery-callback

javascript objects, callback and this keyword


I'm having trouble figuring out how to correctly reference the 'right' 'this' in a jquery ajax callback.

I have a javascript class where I define the callback:

Foo.prototype.onCallback = function(response) {
  // 'this' should refer to an instance of foo in both the following cases
  this.bar(...)    
  this.hello(...)
}

outside of the class I have:

foo1 = new Foo()
myCallback = foo1.onCallback;

$.ajax({
  ...
  success: function(response) {myCallback(response); ... }
});

Right now I believe 'this' within foo1.onCallback is referring to the html element the ajax call is attached to. How do I ensure that 'this' refers to foo1? Is there a better way to do this?


Solution

  • Use the following idiom:

    myCallback = foo1.onCallback.bind(foo1);
    

    In fact you should take advantage of first-class function support in JavaScript even further:

    foo1 = new Foo()
    
    $.ajax({
      ...
      success: foo1.myCallback.bind(foo1)
    });
    

    See also: