Solution for using this keyword in ajax calls inside methods?

I am creating a JavaScript class. Some of the methods contain AJAX calls using jQuery. The problem I am facing is that I cannot use the this in AJAX callbacks due to a change in scope. I came up with a hacky solution, but I wonder what works best for this?

Here is an example:

 var someClass = function() { var someElement = $('form'); this.close = function() { someElement.remove(); }; this.query = function() { $.ajax({ url: someurl, success: function() { this.close(); // does not work because `this` is no longer the parent class } }); }; }; 
+2
source share
3 answers

Just use the context parameter to pass any object you need for a callback:

 $.ajax({ url: someurl, context: this, success: function() { this.close(); // this is what it was when we triggered the AJAX call } }); 

You can also transfer complex objects and more:

 $.ajax({ url: someurl, context: { foo: 'bar', element: this }, success: function() { alert(this.foo); this.element.close(); } }); 
+12
source

Keep a link to this - my convention was to use self .

 var someClass = function() { var self = this, //<--- store a reference someElement = $('form'); this.close = function() { someElement.remove(); }; this.query = function() { $.ajax({ url: someurl, success: function() { self.close(); // does not work because `this` is no longer the parent class } }); }; }; 
+2
source

I prefer to use anonymous functions because you get local variables and you don't need to create variables using var , which I find awkward in the middle of a code block.

 var someClass = function() { var someElement = $('form'); this.close = function() { someElement.remove(); }; this.query = function() { (function(self, someurl){ $.ajax({ url: someurl, success: function() { self.close(); } }); }(this, someurl)); }; }; 

In this example, there is no need to include someurl as a parameter, however, it is useful when you want to make local copies of global variables that can change a value while waiting for a response.

+2
source

All Articles