FinalizationRegistry

 FinalizationRegistry 对象让你可以设置一个回调函数当一个对象被垃圾回收机制回收

说明

FinalizationRegistry 提供一种方法去支持清除的回调函数在注册到注册表的对象已被回收时执行。清理回调函数有时候被称为 finalizers

注意: 清理回调函数不应该用于基本程序逻辑。 参考 Notes on cleanup callbacks

你在回调函数中创建了注册表通道(You create the registry passing in the callback):

const registry = new FinalizationRegistry(heldValue => {
  // ....
});

然后,通过调用“register”方法,传入对象和*held value*来注册任何要进行清理回调的函数:(Then you register any objects you want a cleanup callback for by calling the `register` method, passing in the object and a *held value* for it:)

registry.register(theObject, "some value");

注册不会保持一个对对象的强引用(strong reference), 如果这样就会打破目的(如果注册保持强引用这个对象就永远不会被回收)。

如果 theObject 已经被回收,你的清理回调函数应该被调用在一些你所提供值的点("some value" 在上面)。held value能变成你想要的各种值:一个primitive或者一个对象,甚至是undefined。 如果held value是一个对象,注册表将与他保持一个强引用。(这样,他可以在一段时间后通过他到你的清理回调函数)。

如果你想在一段时间之后注销一个对象,可以通过3个值,这三个值是稍后调用注册表的unregister函数注销对象时将使用的注销标记(unregistration token)。注册仅仅会和注销标记(unregistration token)保持一个弱的引用(weak reference)。

去用对象本身当做注销标记(unregistration token)是非常普遍的:

registry.register(theObject, "some value", theObject);
// ...一些稍后的时间,如果你不关心关于'theObject'的任何事...
// ...some time later, if you don't care about `theObject` anymore...
registry.unregister(theObject);

It doesn't have to be the same object, though; it can be a different one:

registry.register(theObject, "some value", tokenObject);
// ...some time later, if you don't care about `theObject` anymore...
registry.unregister(tokenObject);

Constructor

FinalizationRegistry()
Creates a new FinalizationRegistry object.

Instance methods

FinalizationRegistry.prototype.register()
Registers an object with the registry in order to get a cleanup callback when/if the object is garbage-collected.
FinalizationRegistry.prototype.unregister()
Unregisters an object from the registry.

Avoid where possible

Correct use of FinalizationRegistry takes careful thought, and it's best avoided if possible. It's also important to avoid relying on any specific behaviors not guaranteed by the specification. When, how, and whether garbage collection occurs is down to the implementation of any given JavaScript engine. Any behavior you observe in one engine may be different in another engine, in another version of the same engine, or even in a slightly different situation with the same version of the same engine. Garbage collection is a hard problem that JavaScript engine implementers are constantly refining and improving their solutions to.

Here are some specific points that the authors of the WeakRef proposal that FinalizationRegistry is part of included in its explainer document:

Garbage collectors are complicated. If an application or library depends on GC cleaning up a FinalizationRegistry or calling a finalizer [cleanup callback] in a timely, predictable manner, it's likely to be disappointed: the cleanup may happen much later than expected, or not at all. Sources of variability include:

  • One object might be garbage-collected much sooner than another object, even if they become unreachable at the same time, e.g., due to generational collection.
  • Garbage collection work can be split up over time using incremental and concurrent techniques.
  • Various runtime heuristics can be used to balance memory usage, responsiveness.
  • The JavaScript engine may hold references to things which look like they are unreachable (e.g., in closures, or inline caches).
  • Different JavaScript engines may do these things differently, or the same engine may change its algorithms across versions.
  • Complex factors may lead to objects being held alive for unexpected amounts of time, such as use with certain APIs.

Notes on cleanup callbacks

Some notes on cleanup callbacks:

  • Developers shouldn't rely on cleanup callbacks for essential program logic. Cleanup callbacks may be useful for reducing memory usage across the course of a program, but are unlikely to be useful otherwise.
  • A conforming JavaScript implementation, even one that does garbage collection, is not required to call cleanup callbacks. When and whether it does so is entirely down to the implementation of the JavaScript engine. When a registered object is reclaimed, any cleanup callbacks for it may be called then, or some time later, or not at all.
  • It's likely that major implementations will call cleanup callbacks at some point during execution, but those calls may be substantially after the related object was reclaimed.
  • There are also situations where even implementations that normally call cleanup callbacks are unlikely to call them:
    • When the JavaScript program shuts down entirely (for instance, closing a tab in a browser).
    • When the FinalizationRegistry instance itself is no longer reachable by JavaScript code.

Examples

Creating a new registry

You create the registry passing in the callback:

const registry = new FinalizationRegistry(heldValue => {
  // ....
});

Registering objects for cleanup

Then you register any objects you want a cleanup callback for by calling the `register` method, passing in the object and a *held value* for it:

registry.register(theObject, "some value");

Specifications

Specification
WeakRefs
The definition of 'FinalizationRegistry' in that specification.

Browser compatibility

Update compatibility data on GitHub
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung InternetNode.js
FinalizationRegistryChrome Full support 84Edge Full support 84Firefox Full support 79IE No support NoOpera No support NoSafari No support NoWebView Android Full support 84Chrome Android Full support 84Firefox Android No support NoOpera Android No support NoSafari iOS No support NoSamsung Internet Android No support Nonodejs Full support 13.0.0
Disabled
Full support 13.0.0
Disabled
Disabled From version 13.0.0: this feature is behind the --harmony-weak-refs runtime flag.
FinalizationRegistry() constructorChrome Full support 84Edge Full support 84Firefox Full support 79IE No support NoOpera No support NoSafari No support NoWebView Android Full support 84Chrome Android Full support 84Firefox Android No support NoOpera Android No support NoSafari iOS No support NoSamsung Internet Android No support Nonodejs Full support 13.0.0
Disabled
Full support 13.0.0
Disabled
Disabled From version 13.0.0: this feature is behind the --harmony-weak-refs runtime flag.
registerChrome Full support 84Edge Full support 84Firefox Full support 79IE No support NoOpera No support NoSafari No support NoWebView Android Full support 84Chrome Android Full support 84Firefox Android No support NoOpera Android No support NoSafari iOS No support NoSamsung Internet Android No support Nonodejs Full support 13.0.0
Disabled
Full support 13.0.0
Disabled
Disabled From version 13.0.0: this feature is behind the --harmony-weak-refs runtime flag.
unregisterChrome Full support 84Edge Full support 84Firefox Full support 79IE No support NoOpera No support NoSafari No support NoWebView Android Full support 84Chrome Android Full support 84Firefox Android No support NoOpera Android No support NoSafari iOS No support NoSamsung Internet Android No support Nonodejs Full support 13.0.0
Disabled
Full support 13.0.0
Disabled
Disabled From version 13.0.0: this feature is behind the --harmony-weak-refs runtime flag.

Legend

Full support  
Full support
No support  
No support
User must explicitly enable this feature.
User must explicitly enable this feature.

See also