When I pass 'this' to an anonymous function, for example:
MyClass.prototype.trigger = function(){
window.setTimeout(function(){this.onTimeout();},1000);
}
I get "this.onTimeout not function" -error. I assume that 'this' is no longer available at the time the anonymous function is executed? So I do this:
MyClass.prototype.trigger = function(){
var me = this
window.setTimeout(function(){me.onTimeout();},1000);
}
Is this the way you should do something? It seems to work, but it is strange.
Then we have the following example:
$(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();
});
It is output:
2
2
Should not be output:
1
2
instead of this? Then I found that including the $ .getJSON expression in another function makes everything work:
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); });
}
It is output:
1
2
(Or vice versa). What's going on here? What is the correct way to pass variables into an anonymous function?
Sorry for the confusing and lengthy post.
0scar source
share