0

Mozilla 文档中它说:

initWithCallback():初始化一个定时器,在给定的毫秒间隔后触发。这个版本需要一个函数来调用和一个闭包传递给那个函数。

在此代码示例中:

setupTimer: function() {
    var waitPeriod = getNewWaitPeriod();

    myTimer.initWithCallback({ 
        notify: function(t) {
            foo();
            setupTimer();
        }
    },
    waitPeriod,
    Components.interfaces.nsITimer.TYPE_ONE_SHOT);
}

传递给函数的闭包中实际包含了多少。闭包是否保留了整个堆栈的副本?此代码示例是否存在堆栈溢出或永远增加内存使用量的风险?

4

1 回答 1

0

In theory the closure keeps everything that's in scope for the closure (so in this case the local variables in setupTimer plus whatever variables setupTimer itself closes over). Note that this is different from the callstack: closure scope in JS is lexical, not dynamic, so it doesn't matter how you reached your function, only what the source of the function looks like.

In practice JS engines optimize closures heavily to speed up access to barewords in closures, so the set of things the closure actually keeps alive might be smaller than the theoretical set I describe above. But I wouldn't depend on that.

于 2012-06-16T04:44:17.043 回答