0

My problem is as simple as the title.. I have some code which makes an AJAX call. This code is similar to this (JSFiddle):

function Test() {
    this.name = "U don't wanna know my name..";
}
Test.prototype.ajax = function() {
    $.ajax("url/path", data, function() {
        alert(this.name);
   });
};

var test = new Test();
test.ajax();

In this case this is undefined. I could place the following code before the ajax call and use that in stead of this:

var diz = this;

I was wondering if there's another way of using this without creating a new variable for it.

M Zeinstra
  • 1,931
  • 4
  • 17
  • 46
  • 1
    usually people do `var that = this` or `var _this = this` or `var self = this`. More info http://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-context-inside-a-callback – nada May 24 '16 at 13:34

1 Answers1

1

In this case this is undefined.

this.name is undefined (assuming you meant that), because this is specific to a function's context. Inside that ajax's callback handler this no more belonged to Test, it belonged to that callback function.

was wondering if there's another way of using this without creating a new variable for it.

I don't think that without saving the reference to parent's this (Test's this) you can access this that belonged to a more global scope from a function's scope.

gurvinder372
  • 66,980
  • 10
  • 72
  • 94