递归闭包在JavaScript [英] Recursive closures in JavaScript

查看:90
本文介绍了递归闭包在JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有像

  function animate(param)
{
//。 ..
if(param< 10)
setTimeout(function(){animate(param + 1)},100);
}

animate(0);这意味着函数的本地数据的每个实例都将保存在内存中,直到animate完成,例如,直到(a)到(b)。 param达到10?



如果实例保存在内存中,是否有更好的方法?我知道,传递文本代码到 setTimeout()解决了这个问题,但在我的情况下,函数参数之间的对象不能很容易地表示为字符串

解决方案

不,函数的本地数据的最多两个实例将在任何给定的时间点保存在内存中。这是事件的顺序:


  1. animate(0) / li>
  2. 创建了 param == 0 的关闭,现在可以阻止此变量的释放。

  3. 超时触发, animate(1)被呼叫。

  4. 新的关闭与 param == 1 ,它现在阻止此变量被释放。

  5. 第一个闭包完成执行,此时它不再被引用并可以释放。 $ <$ c $>> animate()调用的局部变量也可以立即释放。

  6. 重复从步骤3开始, c $ c> animate(2)。


Let's say I have something like

function animate(param)
{
    // ...
    if (param < 10)
        setTimeout(function () { animate(param + 1) }, 100);
}

animate(0);

Does this mean each instance of the function's local data will be held in memory until animate completes, i.e. until param reaches 10?

If it's true that instances are held in memory, is there a better way of doing this? I know, passing textual code to setTimeout() solves the problem but in my case there are objects among function arguments that can't be represented as strings easily.

解决方案

No, at most two instances of function's local data will be held in memory at any given point in time. Here is the order of events:

  1. animate(0) is called.
  2. A closure with param == 0 is created, it now prevents this variable from being released.
  3. Timeout fires, animate(1) is called.
  4. New closure with param == 1 is created, it now prevent this variable from being released.
  5. The first closure finishes executing, at this point it is no longer referenced and can be released. The local variables from the first animate() call can also be released now.
  6. Repeat starting with step 3, now with animate(2).

这篇关于递归闭包在JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆