Javascript 对象及其实例和设置超时效果

Javascript 对象及其实例和设置超时效果,javascript,object,greasemonkey,settimeout,Javascript,Object,Greasemonkey,Settimeout,因此,我试图学习javascript中的面向对象编程 function doStock() { //my class var that = this; var nAntiFreeze = null; // timeout ID var getContent = function(oInPageContainer) { GM_log('Antifreeze, before clear ' +nAntiFreeze); //clearTimeout(nAntiFreez

因此,我试图学习javascript中的面向对象编程

function doStock() {    //my class
var that = this;
var nAntiFreeze = null;   // timeout ID
var getContent = function(oInPageContainer) {  
    GM_log('Antifreeze, before clear ' +nAntiFreeze);
    //clearTimeout(nAntiFreeze);
    GM_log('Antifreeze, after clear ' +nAntiFreeze);
};

return {
    sLink : "",
    oList : "",
    sSplitOperator : ";",
    reset : function() {
        this.sLink = '';
        this.oList = '';
        this.sSplitOperator = ';';
        nAntiFreeze = null;
    },
    loadPage : function() {
        if (this.sLink.length == 0) return;
        if (this.oList.length == 0) return;
        nAntiFreeze = setTimeout(function(){GM_log(that); that.loadPage();},30000);
        GM_log('antifreeze ' + nAntiFreeze);
        getPageAsync2(this.sLink,false,getContent);  //GM_xmlhttprequest
    }
}
})

我的脚本在Firefox4的GreaseMonkey上运行。在我的代码中,我使用上述函数/类生成一个对象,如下所示

var oStocker = new doStock();
oStocker.sLink = 'www.somepage.com';
oStocker.oList = 'some list, may be a string line or the array object';
oStocker.loadPage();
getPageAsync2
函数调用GM_xmlhttprequest,然后将div容器中的结果页内容返回给回调函数

首先,一般性问题:在调用
clearTimeOut
函数后,nAntiFreeze的值不会重置为null或任何内容。这正常吗

第二个问题:为什么超时时间结束时,我会得到一个错误,即.loadPage()不是一个函数?GM_log告诉我[object]

在这个问题上,一个人能够通过使用
var-that=this
使它起作用。但是为什么它对我不起作用呢?

编辑:第三个问题:如果我创建了一百万个对象会发生什么。浏览器会在它们完成工作后将其清除吗?因为我确实无法释放它们,因为这个对象使用异步ajax调用,这意味着我不能这样做

var oStocker = new doStock();
oStocker.loadPage();
oStocker = null;
在我的对象完成工作之前,将调用oStocker=null


谢谢

首先,
nAntiFreeze
是由
setTimeout
返回的原始值。您将该值传递回
clearTimtout
,以便它知道要清除哪个超时。调用
clearTimeout
不会影响
nAntiFreeze
的值

其次,
that.loadPage
是未定义的,因为当调用
doStock()
时,
that
引用了
this
(在调用
new
的构造函数时,它引用了一个新对象)。但是您的函数不返回该对象(即构造函数的
this
),而是在
return
之后返回
loadPage()
函数所使用的对象。换句话说,您引用了错误的对象

调用
oStocker.loadPage()
时,其
this
关键字引用
oStocker
对象,但传递给setTimeout的函数引用的是
that
,它对构造函数的
this
有一个闭包

以下方面应起作用:

loadPage : function() {

    // Declare that here
    var that = this;

    if (this.sLink.length == 0) return;
    if (this.oList.length == 0) return;

    // If called as oStocker.loadPage(), this (and that) is
    // the oStocker object.
    nAntiFreeze = setTimeout(function(){GM_log(that); that.loadPage();},30000);
    GM_log('antifreeze ' + nAntiFreeze);
    getPageAsync2(this.sLink,false,getContent);  //GM_xmlhttprequest
}
使用不返回其
this
的构造函数没有多大意义,您可以使用Richard Cornford的模块模式并使用闭包进行继承