Skip to content

Instantly share code, notes, and snippets.

@paulhhowells
Last active May 25, 2022 08:33
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paulhhowells/5430352 to your computer and use it in GitHub Desktop.
Save paulhhowells/5430352 to your computer and use it in GitHub Desktop.
avoid memory leaks with closures. google javascript style guide.
// 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