这个javascript会导致内存泄漏吗?
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不确定第一部分,但关于第二部分有类似的问题:
你知道 JavaScript 中什么可能导致内存泄漏吗?
如何在 Firefox 中跟踪和调试 JavaScript 内存泄漏?
Not sure about first part but there is a similar question about the second part:
Do you know what may cause memory leaks in JavaScript?
How do I track and debug JavaScript memory leaks in Firefox?
使用 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.
回答关于创建内部函数的问题:我相信每次运行
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 afterouter()
runs, along with all the other variables in the function scope - unlessouter()
"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.除非你在里面放入一些其他代码 - 你不应该担心这样简单的闭包中的泄漏。现代 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.