FinalizationRegistry.prototype.register()

FinalizationRegistry 实例的 register() 方法向该 FinalizationRegistry 注册一个值,以便如果该值被垃圾收集,则可能会调用注册表的回调。

¥The register() method of FinalizationRegistry instances registers an value with this FinalizationRegistry so that if the value is garbage-collected, the registry's callback may get called.

语法

¥Syntax

js
register(target, heldValue)
register(target, heldValue, unregisterToken)

参数

¥Parameters

target

要注册的目标值。

heldValue

要传递给此 target 的终结器的值。这不能是 target 本身,而可以是其他任何东西,包括函数和原语。

unregisterToken Optional

稍后可以与 unregister 方法一起使用的令牌,用于取消注册目标值。如果提供(而不是 undefined),则它必须是一个对象或 未注册符号。如果未提供,则无法取消注册目标。

返回值

¥Return value

无 (undefined)。

¥None (undefined).

例外情况

¥Exceptions

TypeError

有下列情况之一的,抛出:

  • target 不是对象或 未注册符号(对象与基元相反;函数也是对象)
  • targetheldvalue (target === heldValue) 相同
  • unregisterToken 不是对象或 未注册符号

描述

¥Description

请参阅 FinalizationRegistry 页的 尽可能避免关于清理回调的注意事项 部分了解重要注意事项。

¥See the Avoid where possible and Notes on cleanup callbacks sections of the FinalizationRegistry page for important caveats.

示例

¥Examples

使用注册

¥Using register

以下注册了 target 引用的值,传入保存的值 "some value" 并将目标本身作为取消注册令牌传递:

¥The following registers the value referenced by target, passing in the held value "some value" and passing the target itself as the unregistration token:

js
registry.register(target, "some value", target);

下面注册了 target 引用的值,传入另一个对象作为持有值,并且不传入任何注销令牌(这意味着 target 无法注销):

¥The following registers the value referenced by target, passing in another object as the held value, and not passing in any unregistration token (which means target can't be unregistered):

js
registry.register(target, { useful: "info about target" });

规范

Specification
ECMAScript Language Specification
# sec-finalization-registry.prototype.register

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看