可能重复:
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()
将“未定义”打印到控制台。为什么会发生这种情况,我该怎么做才能防止这种行为?
答案 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
变量,请注意这一点。