FinalizationRegistry.prototype.unregister()

unregister() 方法是 FinalizationRegistry 实例的方法,用于从此 FinalizationRegistry 中注销目标值。

语法

js
unregister(unregisterToken)

参数

unregisterToken

在注册目标值时,使用 register() 方法使用的令牌。使用相同 unregisterToken 注册的多个单元将一起注销。

返回值

一个布尔值,如果至少注销了一个单元,则为 true;如果未注销任何单元,则为 false

异常

TypeError

如果 unregisterToken 不是对象或 未注册的符号,则抛出此异常。

描述

当目标值已被回收时,它将不再在注册表中注册。无需在清理回调中调用 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 语言规范
# sec-finalization-registry.prototype.unregister

浏览器兼容性

BCD 表格仅在浏览器中加载

另请参阅