简体   繁体   中英

Are event listeners removed when object is set to null in Javascript?

I'm trying to use peer js functionality where we create peers and use the respective event listeners ie when the peer is created, closed, connected and other stuff, and i'm trying to use it inside an event listener to make it work something like a service. Something like this:

class Demo extends EventEmitter {
 private peer: Peer | null = null;

 createPeerConnection() {
  this.peer = new Peer();

  this.peer.on('open', () => {
    // Some stuff done
    this.emit("Peer");
  });

  this.peer.on('close', () => {
    // Some more stuff done
    this.emit("Closed");
  });
 }

 closePeerConnection() {
  this.peer = null;
 }

I know the peer has the destroy method, but let's say if for some reason I set the object to null, will the connected event listeners also be removed?

...when object is set to null in Javascript?

Objects can't be set null in JavaScript, but variables or properties referring to those objects can be. If that variable/property is the only one referring to the object, the object is eligible for garbage collection. So while the event listeners won't be removed per se, in the normal case the object goes away and it doesn't really matter (and if the object was the only thing referencing those event listeners, then they, too, are eligible for garbage collection).

There are things that can get in the way — other references to the object, or in some cases or some environments if the event listeners have a reference to the object, that circuluar relationship can keep them both around (there was a recent bug in browsers around this and ResizeObserver and IntersectionObserver ). But in general, they all just go away (eventually).

To be absolutely sure, of course, proactively remove the listeners.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM