簡體   English   中英

Javascript 相當於對象模型中的 destruct

[英]Javascript's equivalent of destruct in object model

由於我過去處理過 javascript 的時髦“對象模型”,因此我認為沒有析構函數這樣的東西。 我的搜索有點不成功,所以你們是我最后的希望。 你如何在實例銷毀時執行東西?

MDN是一個很好的 JS 資源。 不,沒有什么比在對象停止時調用函數更合適的了。

最近, 此鏈接更適用於回答此問題。 最重要的部分:

截至 2012 年,所有現代瀏覽器都提供了標記和清除垃圾收集器。

...

周期不再是問題

在上面的第一個示例中,在函數調用返回后,這兩個對象不再被可從全局對象訪問的任何資源引用。 因此,垃圾收集器將發現它們無法訪問並回收分配的內存。

限制:手動釋放內存

有時手動決定何時以及釋放什么內存會很方便。 為了釋放一個對象的內存,它需要明確地不可達。

因此,就循環引用而言,實際上並不需要 de[con]structors。


不過,我想到了一個很酷的技巧,如果您有循環引用並且想要輕松手動控制解構...

class Container {
  constructor() {
    this.thisRef = [ this ];
    this.containee = new Containee({ containerRef: this.thisRef });
  }

  //Note: deconstructor is not an actual JS thing/keyword.
  deconstructor() {
    //Have to delete `this.thisRef[0]` and not `this.thisRef`, in
    //order to ensure Containee's reference to Container is removed.
    delete this.thisRef[0];
  }

  doSomething() {

  }
}

class Containee {
  constructor({ containerRef }) {
    //Assumption here is, if the Container is destroyed, so will the Containee be
    //destroyed. No need to delete containerRef, no need for a
    //deconstructor function!
    this.containerRef = containerRef;
  }

  someFunc() {
    this.containerRef[0].doSomething();
  }
}

let c = new Container();
...
//No cyclic references!
c.deconstructor();

因此,在這里,不是 Container 類存儲對 Container 實例的直接引用,而是存儲對包含 Container 引用的大小為 1 的數組的引用,然后 Container 實例本身可以從 中刪除自己 帶有引用的數組由 Container 管理。

但同樣,這並不是真正需要的,因為所有現代瀏覽器中的垃圾收集都是標記和清除並且可以處理循環引用。

在其他語言中,析構函數對於實現備忘錄模式很方便。 這實際上是導致我進入這個話題的原因。 例如,在點擊事件中,最好有一個通用函數,我可以將事件目標傳遞給禁用目標,然后在它超出范圍時重新啟用它。 考慮一個執行如下操作的提交按鈕:

function async saveMyStuff(e) {
    const sleeper = new nap(e)
    let data = await fetch(...)
    // a bunch more code.
}

class nap {
    constructor(e) {
      this.button = e.currentTarget
      this.button.disabled = true
    }
    destructor() { this.button.enabled = true }

}

這種構造會給我一個oneliner,當我與后端交談或進行任何其他處理時,它可以處理啟用/禁用我的所有按鈕。 如果我在中間的某個地方或類似的地方返回,我不必擔心清理。

FinalizationRegistry可能正是您所需要的。 它不是析構函數,但是一旦對象被垃圾回收,它就會執行一個函數。 無論如何,這就是我第一次來到這里時希望找到的東西:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM