当我将'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语句放在另一个函数中可以使它正常工作:
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
(或者反过来。)这里发生了什么?传递变量给匿名函数的正确方法是什么?
抱歉,文章有些混乱和冗长。