如果我使用这段代码为什么范围变更为“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);
你应该可以指定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);
编辑我做了一个小提琴 ,这和验证其工作正常。 有没有乱搞一个额外的self
参数或有渣土周围的封锁,让您的变量。
你失踪哪一部分被调用onComplete.call(this, data)
来调用doStuff()
我已经改变了你的代码的引用传递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);