0

Assume that I have an HTML list <ul> and I add <li> items dynamically with JS. So the list becomes like this:

<ul id="parent">
  <li> //container
  Some text <button>Delete</button>
  </li>
</ul>

Here, the <button> is used to delete the <li> using JS. I created a class with a delete method to delete the <li> when the button is clicked:

class MyObj {
  constructor(parent, container) {
    this.parent = parent;
    this.container = container;
  }

  delete() {
    this.parent.removeChild(this.container);
  }
}

And this is the function that is used to create <li> elements:

function create() {
  let container = document.createElement('li');
  let deleteContainerBtn = document.createElement('button');

  container.innerHTML = "Sometext";
  container.appendChild(deleteContainerBtn);
  parent.appendChild(container);

  const obj = new MyObj(parent, container, deleteContainerBtn);
  
  deleteContainerBtn.onclick = function() {
    obj.delete()
  };
};

This works fine (I add <li> containers with function create as many times as I want and they can be deleted when I click their Delete buttons). How? When function create is done executing, isn’t obj supposed to be deleted? How does it perform the delete method if it is deleted?

2
  • 1
    function() { obj.delete() } is a closure that closes over obj. Since it references it internally, obj can never get garbage collected, unless the closure itself is not referenced by anything. Aside: prefer addEventListener over .onclick. Commented Dec 4, 2022 at 17:04
  • 1
    simply speaking, if you can refer to it, it would be alive. (if you're worry about lifetime issue) Commented Dec 4, 2022 at 17:08

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.