Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'this' reference in JavaScript

I have a little problem in object programming in javascript

There is a "class" Task, it has several methods, a method containing an asynchronous sending of a request with a help of JQuery ($.ajax). After request is success it's necessary to perform a particular method (e.g. successFunction) of the class Task.

The problem is, after the query in the body of successFunction it's impossible to refer to the class using the keyword this, because the context has changed, and this contains a reference to the jquery-object which performs an ajax-request.

What variants to refer to the current Task object inside a function that was not caused directly but externally exist? (For example by an event or ajax)

like image 655
JN0iZzze Avatar asked Feb 05 '12 13:02

JN0iZzze


1 Answers

Normally inside an AJAX event such as the success callback, this refers to the object returned by the $.ajax call. You could use the context parameter to change the context in the success callback:

$.ajax({
    url: '/foo',
    context: this, // <!-- change the context of the success callback
    success: function(result) {
        // 'this' here will refer to whatever it refered outside
    } 
});

You could also pass complex objects:

$.ajax({
    url: '/foo',
    context: { element: this, foo: 'bar' },
    success: function(result) {
        // you can use 'this.element' and 'this.foo' here
    } 
});
like image 164
Darin Dimitrov Avatar answered Nov 02 '22 23:11

Darin Dimitrov