Javascript 如何获取对象的实例名

Javascript 如何获取对象的实例名,javascript,class,polling,webmethod,Javascript,Class,Polling,Webmethod,我使用下面的代码编写代码,在指定的时间间隔内查询web方法。 现在在this.Poll函数中我必须做 this.tmo = setTimeout(this.strInstanceName + ".Poll()", this.iInterval); 而不是 this.tmo = setTimeout(this.Poll(), this.iInterval); 因为IE在setTimeout之后松开了这个指针 所以我必须传递类的实例名: var objPoll = new cPoll

我使用下面的代码编写代码,在指定的时间间隔内查询web方法。

现在在this.Poll函数中我必须做

this.tmo = setTimeout(this.strInstanceName + ".Poll()", this.iInterval);
而不是

this.tmo = setTimeout(this.Poll(), this.iInterval);
因为IE在setTimeout之后松开了这个指针
所以我必须传递类的实例名:

    var objPoll = new cPoll("objPoll");

如何在不将实例名作为参数传递的情况下获取实例名?
我想把它弄出去!


间隔试验
功能测试()
{
警报(“测试”);
test.tmo=设置超时(test,2000);
test.Clear=函数()
{
clearTimeout(test.tmo);
}
}
函数cPoll(strInstanceName)
{
this.strInstanceName=strInstanceName;
这个区间=2000;
tmo=null;
this.cbFunction=null;
this.Poll=函数()
{
这个.cbFunction();
this.tmo=setTimeout(this.strInstanceName+“.Poll()”,this.iInterval);
}
this.Start=函数(pCallBackFunction,iIntervalParameter)
{
如果(this.tmo!=null)
这个。停止();
如果(iIntervalParameter&&iIntervalParameter>0)
此.iInterval=iInterval参数;
this.cbFunction=pCallBackFunction;
if(this.cbFunction!=null)
这个。Poll();
其他的
警报(“无效或未指定回调函数”);
}
this.Stop=function()
{
如果(this.tmo!=null)
{
clearTimeout(this.tmo);
tmo=null;
}
}
}
函数CallBackFunction()
{
警报(“轮询回调”);
}
//test();
//test.Clear();
var objPoll=新cPoll(“objPoll”);
试验

松开
this.Poll()中的括号。
。您可以立即调用此函数,而不是在一段时间间隔后调用。如果您松开括号,它将传递一个函数,而不是它的结果,到
setInterval
,您将不会有任何问题

setTimeout(this.Poll, this.Interval);
否则,您立即调用该函数,并且不再有任何内容保存该指针,IE只是删除它


在固定变量中,
this.Poll
将保留指向
this
的指针,并且不会被删除。

今天我为一个类似的问题提供了答案,在这个问题中,我从头创建了一个轮询类。你可能想自己采用它。为了避免重复,这里有一个链接到上述问题:

var self = this;
this.tmo = setTimeout(function(){
     self.Poll();
}, this.iInterval);
*


*尽管有标题,我的解决方案还是提供了“香草”和Dojo风格。

您可以使用这个方便的小包装器以给定的间隔(默认为1秒)定期执行函数:

重复该函数,直到返回false:

tick(function() {
   if(should stop) return false;
   do stuff
   return true;
});
如果函数是一个方法,则创建一个闭包,如图所示

// inside your object
var me = this;
tick(function() {
   return me.doStuff();
});

我问了另一个问题,答案如下:


反复遍历全局变量并检查它是否等于“this”。

我只是想说,这种自我技巧帮我省去了很多麻烦

我没想到会创建这样的引用。这意味着使用单击事件动态创建的元素可以调用my类的正确实例。

您还可以使用:

i、 e


即使没有支架,灾难也会降临。你用IE吗8?用J-P发布的
self
。如果这不起作用,那么在调用
Start
之前,您的对象正在进行GC(或尚未创建)。因此,在调用
Start()
之前,确保objPoll在那里,并尝试在
objPoll=newcpoll(“objPoll”)之前释放
var
GC是可能的,但当我单击Start时它就在那里,因为Start是从实例调用的。如果它不存在,它就不会启动。
this=pointerToInstanceInMemory
,因此,
self=pointerToInstanceInMemory
@J-P:我的意思是创建一个指向空对象的别名意味着别名也为空…
在JavaScript中,这不能是
null
。这是不可能的,为什么不呢?指针可以始终为空。显然这是可能的,至少在IE8中是肯定的,我不认为这是可能的。请让我知道是什么代码使得
这个===null
。。。
tick(function() {
   if(should stop) return false;
   do stuff
   return true;
});
// inside your object
var me = this;
tick(function() {
   return me.doStuff();
});
var name = findInstanceOf(cPoll);

function findInstanceOf(obj) {
    for (var v in window) {
        try {
            if (window[v] instanceof obj)
                return v;
        } catch(e) { }
    };
    return false;
}