My question is about js object created and stored in function. What do they becomes once the function returns? Here is a code example:
class userInfo {
constructor(name, age) {
this.name = name;
this.age = age;
}
function greetings() {
alert(`Hi, you're name is ${this.name} and you are ${this.age}`);
}
function renderUserInfos() {
const userContent = document.createElement('ul');
userContent.innerHTML = `
<li>${this.name}</li>
<li>${this.age}</li>
<button>Display User Info </button>
`
const displayButton = userContent.querySelector('button');
displayButton.addEventListener('click',this.greetings.bind(this));
}
}
function render(name, age) {
const user = new userInfo(name, age);
user.renderUserInfos();
return;
}
render('John',25);
Now I expect the "displayButton" to trigger the "greetings" function, once I’ll click on it.
However, as the "user" object that has been created in the "render" function will be garbage collected once this function will return, how can the "greetings" function be triggered??
2
Answers
The
userInfo
object you create inrender
has two references to it: a local variableuser
and the bind context created bythis.greetings.bind
. Once you exitrender
, the first reference is cleared, but the second is not. Since the object has the reference count > 0 it won’t be collected.In general you should not worry about garbage collection.
According to this article on medium there are 3 common mistakes you should keep in mind:
Excessive use of globals by creating global variables or by omitting
the var keyword in local scope
Forgetting the clearing of timers like setInterval()
Unnecessary use of closures
REMEMBER
Closures always keep a reference of the variables from the parent function even if the parent function has completed execution.
So to answer your question:
The object ‘userInfo’ does not get garbage collected