skip to Main Content

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


  1. The userInfo object you create in render has two references to it: a local variable user and the bind context created by this.greetings.bind. Once you exit render, the first reference is cleared, but the second is not. Since the object has the reference count > 0 it won’t be collected.

    Login or Signup to reply.
  2. 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:

    1. Excessive use of globals by creating global variables or by omitting
      the var keyword in local scope

    2. Forgetting the clearing of timers like setInterval()

    3. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search