Suppose I have function that returns a method of an object that only exists in stack scope:
class Item {
constructor(name) { this.name = name }
print() { console.log(`Item with name: ${this.name}`); }
}
function namePrinter(name) {
return (new Foo(name)).bar
}
const printer = namePrinter('Alan')
printer() // prints 'Alan'
Does the reference to the print() method prevent the Foo instance from being garbage collected? My assumption is that underneath the ES6 OO sugar the bar() method gets bound to the Foo instance, causing it to store a reference to the object so that it can substitute it into this, but I'm not sure.
Side note - I realize I could make this work with something like the following, where the instance is part of the closure to an anonymous function, but that wouldn't work for my particular use case:
function newPrinter(name) {
const item = new Item(name)
return () => {
item.print()
}
}