当我将“this”传递给这样的匿名函数时:
MyClass.prototype.trigger = function(){
window.setTimeout(function(){this.onTimeout();},1000);
}
我收到“this.onTimeout 不是函数”错误。我猜想在匿名函数执行时“this”不再可用?所以我一直在这样做:
MyClass.prototype.trigger = function(){
var me = this
window.setTimeout(function(){me.onTimeout();},1000);
}
这真的是你应该做的事情吗?它有点工作,但感觉很奇怪。
然后我们有这个例子:
$(function(){
function MyClass(){
this.queue = new Array();
}
MyClass.prototype.gotAnswer = function(count){
$('body').append("count:"+count+"<br/>");
}
MyClass.prototype.loadAll = function(){
var count = 0;
var item;
while(item = this.queue.pop()){
count++;
var me = this;
$.getJSON("answer.html",{},function(data){me.gotAnswer(count);});
}
}
var o = new MyClass();
o.queue.push(1);
o.queue.push(2);
o.loadAll();
});
这输出:
2
2
它不应该输出:
1
2
反而?然后我发现将 $.getJSON-statement 放在另一个函数中可以使它全部工作:
MyClass.prototype.loadAll = function(){
var count = 0;
var item;
while(item = this.queue.pop()){
count++;
this.newRequest(count);
}
}
MyClass.prototype.newRequest = function(count){
var me = this;
$.getJSON("answer.html",null,function(data){ me.gotAnswer(count); });
}
这输出:
1
2
(或相反。)这里发生了什么?将变量传递给匿名函数的正确方法是什么?
很抱歉这篇令人困惑和冗长的帖子。