FinalizationRegistry.prototype.unregister()
FinalizationRegistry
实例的 unregister()
方法从该 FinalizationRegistry
中取消注册目标值。
¥The unregister()
method of FinalizationRegistry
instances unregisters a target value from this FinalizationRegistry
.
语法
参数
返回值
例外情况
描述
¥Description
当目标值被回收后,它就不再在注册表中注册。无需在清理回调中调用 unregister
。仅当你未收到清理回调且不再需要接收时才调用 unregister
。
¥When a target value has been reclaimed, it is no longer registered in the registry.
There is no need to call unregister
in your cleanup callback. Only call
unregister
if you haven't received a cleanup callback and no longer need
to receive one.
示例
使用注销
¥Using unregister
此示例显示使用与取消注册令牌相同的对象来注册目标对象,然后通过 unregister
取消注册它:
¥This example shows registering a target object using that same object as the unregister
token, then later unregistering it via unregister
:
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
}
}
此示例显示使用不同的对象作为其取消注册令牌来注册目标对象:
¥This example shows registering a target object using a different object as its unregister token:
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;
}
}
}
规范
Specification |
---|
ECMAScript Language Specification # sec-finalization-registry.prototype.unregister |
浏览器兼容性
BCD tables only load in the browser
也可以看看
¥See also