我使用下面的代码编写代码来查询指定时间间隔内的Web方法。
现在在 this.Poll 函数中我必须做
this.tmo = setTimeout(this.strInstanceName + ".Poll()", this.iInterval);
代替
this.tmo = setTimeout(this.Poll(), this.iInterval);
因为IE在setTimeout之后丢失了this指针
所以我必须传递该类的实例名称:
var objPoll = new cPoll("objPoll");
如何获取实例名称而不将其作为参数传递?
我想把它带出去!
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Intervall-Test</title>
<script type="text/javascript" language="javascript">
function test()
{
alert("Test");
test.tmo = setTimeout(test, 2000);
test.Clear = function()
{
clearTimeout(test.tmo);
}
}
function cPoll(strInstanceName)
{
this.strInstanceName = strInstanceName ;
this.iInterval = 2000;
this.tmo=null;
this.cbFunction=null;
this.Poll = function()
{
this.cbFunction();
this.tmo = setTimeout(this.strInstanceName + ".Poll()", this.iInterval);
}
this.Start = function(pCallBackFunction, iIntervalParameter)
{
if(this.tmo != null)
this.Stop();
if(iIntervalParameter && iIntervalParameter > 0)
this.iInterval=iIntervalParameter;
this.cbFunction=pCallBackFunction;
if(this.cbFunction!=null)
this.Poll();
else
alert("Invalid or no callback function specified");
}
this.Stop = function()
{
if(this.tmo != null)
{
clearTimeout(this.tmo);
this.tmo=null;
}
}
}
function CallBackFunction()
{
alert("PollCallBack");
}
// test();
// test.Clear();
var objPoll = new cPoll("objPoll");
</script>
</head>
<body>
<h1>Test</h1>
<input type="Button" value="Start polling" onclick="objPoll.Start(CallBackFunction,3000);" />
<input type="Button" value="Stop polling" onclick="objPoll.Stop();" />
</body>
</html>
松开其中的括号this.Poll()
。您立即调用此函数,而不是经过一段时间后。如果松开括号,它将传递一个函数,而不是它的结果,setInterval
你不会有任何问题。
setTimeout(this.Poll, this.Interval);
否则你立即调用该函数并且什么都不会发生this
指针不再存在了,我刚刚删除了它。
在固定变体中,this.Poll
将持有指向this
并且它不会被删除。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)