FinalizationRegistry.prototype.unregister()

Baseline 廣泛可用 *

此特性已得到良好支援,可在多種裝置和瀏覽器版本上使用。自 2021 年 4 月起,所有瀏覽器均已支援此特性。

* 此特性的某些部分可能存在不同級別的支援。

unregister() 方法是 FinalizationRegistry 例項的方法,用於將目標值從此 FinalizationRegistry 中登出。

語法

js
unregister(unregisterToken)

引數

unregisterToken

在註冊目標值時與 register() 方法一起使用的令牌。使用相同 unregisterToken 註冊的多個單元將一起被登出。

返回值

如果至少有一個單元被登出,則返回 true;如果沒有任何單元被登出,則返回 false

異常

TypeError

如果 unregisterToken 不是物件或 未註冊的 Symbol,則會丟擲此錯誤。

描述

當目標值已被回收時,它將不再在登錄檔中註冊。無需在清理回撥中呼叫 unregister。只有當您未收到清理回撥且不再需要接收清理回撥時,才應呼叫 unregister

示例

使用 unregister

此示例演示瞭如何使用目標物件本身作為登出令牌來註冊一個目標物件,然後在稍後透過 unregister 登出它。

js
class Thingy {
  static #cleanup = (label) => {
    //               ^^^^^−−−−− held value
    console.error(
      `The "release" method was never called for the object with the label "${label}"`,
    );
  };
  #registry = new FinalizationRegistry(Thingy.#cleanup);

  /**
   * Constructs a `Thingy` instance.
   * Be sure to call `release` when you're done with it.
   *
   * @param label A label for the `Thingy`.
   */
  constructor(label) {
    //                            vvvvv−−−−− held value
    this.#registry.register(this, label, this);
    //          target −−−−−^^^^         ^^^^−−−−− unregister token
  }

  /**
   * Releases resources held by this `Thingy` instance.
   */
  release() {
    this.#registry.unregister(this);
    //                        ^^^^−−−−− unregister token
  }
}

此示例演示瞭如何使用不同的物件作為其登出令牌來註冊一個目標物件。

js
class Thingy {
  static #cleanup = (file) => {
    //               ^^^^−−−−− held value
    console.error(
      `The "release" method was never called for the "Thingy" for the file "${file.name}"`,
    );
  };
  #registry = new FinalizationRegistry(Thingy.#cleanup);
  #file;

  /**
   * Constructs a `Thingy` instance for the given file.
   * Be sure to call `release` when you're done with it.
   *
   * @param filename The name of the file.
   */
  constructor(filename) {
    this.#file = File.open(filename);
    //                            vvvvv−−−−− held value
    this.#registry.register(this, label, this.#file);
    //          target −−−−−^^^^         ^^^^^^^^^^−−−−− unregister token
  }

  /**
   * Releases resources held by this `Thingy` instance.
   */
  release() {
    if (this.#file) {
      this.#registry.unregister(this.#file);
      //                        ^^^^^^^^^^−−−−− unregister token
      File.close(this.#file);
      this.#file = null;
    }
  }
}

規範

規範
ECMAScript® 2026 語言規範
# sec-finalization-registry.prototype.unregister

瀏覽器相容性

另見