Skip to content

Instantly share code, notes, and snippets.

@garlicnation
Last active December 21, 2016 00:02
Show Gist options
  • Save garlicnation/aca6e7dc6ba9f65232e10c5ebfc3ff0d to your computer and use it in GitHub Desktop.
Save garlicnation/aca6e7dc6ba9f65232e10c5ebfc3ff0d to your computer and use it in GitHub Desktop.
// Hat tip to Adam Klein for an explanation.
// v8's code generation goes through phases that roughly correspond to:
// Parse -> Analyze -> Generate Code
// During Parse/analyze, v8 tracks which variables in scope are used by closures in that scope
// All closures declared in a function keep references to any variables used by any closure
// in that function.
// In the following example, each function returned by retainTooMuch will retain bbz, even though
// the returned closure doesn't reference that variable, because another closure in the same scope
// did reference bbz.
function retainTooMuch() {
var aaz = [1,2,3]; var bbz = [2,3,4];
var y = () => bbz;
return function(arg){return console.log(aaz)};
}
b = retainTooMuch();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment