这个javascript会导致内存泄漏吗?

发布于 2024-12-07 15:41:17 字数 363 浏览 0 评论 0原文

function outer(){
  var a, b, c;

  function inner1(){
    ...
  }

  function inner2(){
    ...
  }

  inner1();
  inner2();
  ...
}

我想保持全局命名空间干净,所以我写了上面的代码。内部函数仅由外部内部的代码使用。但之后我开始思考这是否会导致任何记忆问题。我不确定内部函数是预先创建的还是每次调用 external() 时创建的?它们会导致内存泄漏吗?

有人可以帮助解释当调用outer()以及它返回时会发生什么吗?如果有关于javascript内存管理的好书或文章请推荐给我。我总是被这样的问题搞糊涂。谢谢。

function outer(){
  var a, b, c;

  function inner1(){
    ...
  }

  function inner2(){
    ...
  }

  inner1();
  inner2();
  ...
}

I want to keep the global namespace clean so I wrote above code. Inner functions are only used by code inside Outer. But after that I begin to thought if this will cause any memory problem. I'm not sure whether the inner functions are created beforehand or created each time the outer() is called? And will them cause memory leak?

Could someone help explain what will happen when outer() is called and when it returns? And please refer me if there are any good books or articles about javascript memory management. I always get confused by such problems. Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

堇年纸鸢 2024-12-14 15:41:17

使用 JavaScript 的浏览器中导致内存泄漏的主要问题是 DOM 和 JS 有两个独立的垃圾收集器。如果您开始在闭包函数中引用 DOM 元素,然后再次反向引用函数内部的某些内容,您将面临问题。您的结构没有泄漏,但您想做更多的事情,这可能会泄漏。

The main problem that causes memory leaks in browsers with JavaScript is the fact, that the DOM and JS have two independet garbage collectors. If you begin to have references to DOM elements in your closure function and then again backreference to something inside the function you will face problems. Your structure is not leaking, but you want to do some more stuff and that maybe leaking.

朮生 2024-12-14 15:41:17

回答关于创建内部函数的问题:我相信每次运行 outer() 时都会创建/定义内部函数,并且大多数 JS 解释器应该在 之后对它们进行垃圾收集external() 与函数作用域中的所有其他变量一起运行 - 除非 outer() 将这些内部函数“导出”到其自身作用域之外,例如将它们分配为事件处理程序或将它们包含在return 语句供以后使用。

In answer to your question about the creation of the inner functions: I believe your inner functions are created/defined every time you run outer(), and most JS interpreters should garbage-collect them after outer() runs, along with all the other variables in the function scope - unless outer() "exports" these inner functions outside of its own scope, e.g. assigning them as event handlers or including them in a return statement for later use.

夏の忆 2024-12-14 15:41:17

除非你在里面放入一些其他代码 - 你不应该担心这样简单的闭包中的泄漏。现代 javascript 引擎可以很好地处理这些问题。

Unless you put some other code inside - you should not worry about leaks in such simple closures. Modern javascript engines handle those very well.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文