如果我使用此代码,为什么“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);
答案 0 :(得分:5)
您应该能够将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);
修改我为此做了fiddle并验证它是否正常运行。有一个额外的self
参数,或者不得不用闭包来保存你的变量。
您缺少的部分内容是调用onComplete.call(this, data)
来调用doStuff()
。
答案 1 :(得分:3)
我已修改您的代码以将对this
的引用传递到doStuff()代码。
(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,self);
}
});
alert('doAjax1 self === c$.oTestScope: ' + (self === c$.oTestScope).toString());
};
this.doStuff = function (data,thisRef) {
var self = thisRef;
alert('doStuff self === c$.oTestScope: ' + (self === c$.oTestScope).toString());
}
};
c$.oTestScope = new c$.TestScope();
c$.oTestScope.doAjax(c$.oTestScope.doStuff);
})(jQuery);