Will this javascript cause a memory leak?

function outer(){ var a, b, c; function inner1(){ ... } function inner2(){ ... } inner1(); inner2(); ... } 

I want the global namespace to be clean, so I wrote the code above. Internal functions are used only by code inside Outer. But after that, I start to think that this will cause a memory problem. I'm not sure if internal functions were created in advance or created every time external () is called? And will they cause a memory leak?

Can someone help explain what happens when the external () function is called and when it returns? And please write to me if there are good books or articles about javascript memory management. I always confuse such problems. Thanks.

+4
source share
4 answers

In response to your question about creating internal functions: I believe that your internal functions are created / defined every time you run outer() , and most JS interpreters should collect garbage after outer() , as well as all other variables in the function area - if outer() does not "export" these internal functions outside its own scope, for example, assigning them as event handlers or including them in a return statement for later use.

0
source

Not sure about the first part, but there is a similar question about the second part:

Do you know what could cause a memory leak in JavaScript?

How to track and debug JavaScript memory leaks in Firefox?

+2
source

The main problem that causes memory leak in JavaScript browsers is that the DOM and JS have two independent garbage collectors. If you start referencing DOM elements in your closure function, and then backtracking to something inside the function again, you will run into problems. Your structure is not leaking, but you want to do a few more things and maybe leak.

+1
source

If you do not enter any other code inside, you should not worry about leaks in such simple closures. Modern javascript engines do a great job of this.

0
source

All Articles