Skip to content

Instantly share code, notes, and snippets.

@thomastay
Last active October 19, 2020 17:09
Show Gist options
  • Save thomastay/7c43a411bbb6bd6733859f9bc99be755 to your computer and use it in GitHub Desktop.
Save thomastay/7c43a411bbb6bd6733859f9bc99be755 to your computer and use it in GitHub Desktop.
Easy to forget memory leaks
// Case 1: accidentally capturing an outer object in a lambda
class Foo {
constructor(arr) {
this.sayHellos = [];
for (const languageData of arr) {
this.sayHellos.push(() => {
console.log(languageData.hello); // oops, languageData is captured, even though it is not needed after this call
});
};
}
}
const arr = [{language: "English", hello: "Hello!"}, {language: "Chinese", hello: "Ni Hao!"}];
const foo = new Foo(arr);
for (const f of foo.sayHellos) {
f();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment