我写了下面的函数。将本地函数传递给setTimeout()
function obj()
{
this.a;
}
obj.prototype.catch = function()
{
alert('Catched')
}
obj.prototype.do = function()
{
alert('called');
}
我需要的是,之后的obj ::做电OBJ ::赶上()()被调用,调用必须从OBJ :: DO(内部进行) 因此,如何通过本地obj的功能的setTimeout
我曾尝试
obj.prototype.do = function()
{
window.setTimeout('"'+this.catch+'()"',1000);
alert('called');
}
它不工作 然后我试图
obj.prototype.do = function()
{
window.setTimeout('"'+this+'.catch()"',1000);
alert('called');
}
这给了我下面的错误铬控制台
Uncaught SyntaxError: Unexpected token ILLEGAL
,所以我尝试了以下方法脏(是不是真的脏吗?)
obj.prototype.do = function()
{
this.pid = randomVal(100);
window['temp'+this.pid] = this;
window.setTimeout("temp"+this.pid+".catch();",1000);
alert('called');
}
function randomVal(bound)//returns a random number between 0 and <bound>
{
return (Math.floor(Math.random()*(bound)));
}
这工作。
那么为什么前两种方法不worked.Is有任何其他的方式做同样的事情,没有全局变量.. 第二种方法和最后一个方法几乎相同。但是为什么我在gettng第二种方法的错误。 。? 的工作代码可以在这里找到 http://jsfiddle.net/jXhAs/
当我们可以在'do'函数中创建一个本地作用域变量时,不需要引入* another *匿名函数。 – Quentin 2012-04-17 14:58:34
@Quentin:有趣的是,这正是Neals的例子(如果你想象他的代码中包含“obj.prototype.do = function(){}”),那么你会批评他。我想有人正在寻求接受这里;-) – micha 2012-04-18 15:24:47