2

Possible Duplicate:
Why doesn't this closure have access to the 'this' keyword? - jQuery

function class1() {
    this.url = 'http://en.wikiquote.org/w/api.php?action=query&format=json&prop=revisions&titles=Albert_Einstein&rvprop=content&callback=?';

    this.f = function() {
        $.getJSON(this.url, function() {
            console.log(this.url);
        });
    }
};

var obj = new class1();
obj.f();

Instead of printing the url, obj.f() prints "undefined" to the console. Why is this happening and what can I do to prevent this behaviour?

Community
  • 1
  • 1
Sergey
  • 47,222
  • 25
  • 87
  • 129

2 Answers2

4

Inside your ajax callback, this will be the jqXhr object, not your current object. You'll want to save the value of this before your ajax call, and reference that in your callback:

this.f = function() {
    var self = this;
    $.getJSON(this.url, function() {
        console.log(self.url);
    });
}
Adam Rackis
  • 82,527
  • 56
  • 270
  • 393
2

How about saving the url variable as a local using the var statement:

function class1() {
    var url = 'http://en.wikiquote.org/w/api.php?action=query&format=json&prop=revisions&titles=Albert_Einstein&rvprop=content&callback=?';

    this.f = function() {
        $.getJSON(url, function() {
            console.log(url);
        });
    }
};

This makes the url variable private; just be aware of that if you are trying to access the url variable outside of the class1 function.

Jasper
  • 75,717
  • 14
  • 151
  • 146