从$ .getJSON调用外部对象

时间:2012-01-30 17:53:59

标签: javascript jquery ajax multithreading getjson

  

可能重复:
  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();

而不是打印网址,obj.f()将“未定义”打印到控制台。为什么会发生这种情况,我该怎么做才能防止这种行为?

2 个答案:

答案 0 :(得分:4)

在你的ajax回调中,this将是jqXhr对象,而不是你当前的对象。您需要在ajax调用之前保存this的值,并在回调中引用

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

答案 1 :(得分:2)

如何使用url语句将var变量保存为本地:

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);
        });
    }
};

这使url变量成为私有的;如果您尝试访问url函数之外的class1变量,请注意这一点。