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?

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
  • 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`](//developer.mozilla.org/en/docs/Web/API/EventTarget/addEventListener) over `.onclick`. – Sebastian Simon Dec 04 '22 at 17:04
  • 1
    simply speaking, if you can refer to it, it would be alive. (if you're worry about lifetime issue) – apple apple Dec 04 '22 at 17:08

0 Answers0