FinalizationRegistry.prototype.unregister()
Baseline 广泛可用 *
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 |
浏览器兼容性
加载中…