bco*_*rad 1 ajax jquery scope callback
如果我使用此代码,为什么"doStuff"警报的范围已更改?有没有办法确保范围是我的对象而不是Window对象?
这是jsfiddle中的相同代码.
(function ($) {
var c$ = {};
c$.TestScope = function () {
this.doAjax = function (onComplete) {
var self = this;
$.ajax({
url: 'badurl',
complete: function (data) {
alert('doAjax2 self === c$.oTestScope: ' + (self === c$.oTestScope).toString());
onComplete(data);
}
});
alert('doAjax1 self === c$.oTestScope: ' + (self === c$.oTestScope).toString());
};
this.doStuff = function (data) {
var self = this;
alert('doStuff self === c$.oTestScope: ' + (self === c$.oTestScope).toString());
}
};
c$.oTestScope = new c$.TestScope();
c$.oTestScope.doAjax(c$.oTestScope.doStuff);
})(jQuery);?
Run Code Online (Sandbox Code Playgroud)
您应该能够将this值指定为参数中的上下文$.ajax():
var c$ = {};
c$.TestScope = function() {
this.doAjax = function(onComplete) {
alert('doAjax1 this === c$.oTestScope: ' + (this === c$.oTestScope).toString());
$.ajax({
url: 'badurl',
context: this,
complete: function(data) {
alert('doAjax2 this === c$.oTestScope: ' + (this === c$.oTestScope).toString());
onComplete.call(this, data);
}
});
};
this.doStuff = function(data) {
alert('doStuff this === c$.oTestScope: ' + (this === c$.oTestScope).toString());
}
};
c$.oTestScope = new c$.TestScope();
c$.oTestScope.doAjax(c$.oTestScope.doStuff);
Run Code Online (Sandbox Code Playgroud)
编辑我为此做了一个小提琴并验证它是否正常工作.有一个额外的self参数没有搞乱,或者不得不用闭包来保持你的变量.
你错过的部分原因是要求onComplete.call(this, data)调用doStuff().