Last active
May 25, 2022 08:33
-
-
Save paulhhowells/5430352 to your computer and use it in GitHub Desktop.
avoid memory leaks with closures. google javascript style guide.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// from google javascript style guide: | |
// One thing to keep in mind, however, is that a closure keeps a pointer to its enclosing scope. As a | |
// result, attaching a closure to a DOM element can create a circular reference and thus, a memory leak. | |
// For example, in the following code: | |
// Leaky example | |
function foo (element, a, b) { | |
element.onclick = function() { | |
// uses a and b | |
// this func keeps a pointer to foo, its enclosing scope | |
// this func is attached to element, which thus keeps a pointer to foo and its variables - a, b, element | |
}; | |
} | |
// the function closure keeps a reference to element, a, and b even if it never uses element. Since element | |
// also keeps a reference to the closure, we have a cycle that won't be cleaned up by garbage collection. | |
// In these situations, the code can be structured as follows: | |
// Solution example | |
function foo (element, a, b) { | |
element.onclick = bar(a, b); | |
} | |
function bar (a, b) { | |
return function() { | |
//uses a and b | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment