Is it possible to create a “weak reference” in javascript?

前端 未结 9 1726
忘掉有多难
忘掉有多难 2020-11-28 04:53

Is there any way in javascript to create a \"weak reference\" to another object? Here is the wiki page describing what a weak reference is. Here is another article that desc

9条回答
  •  悲&欢浪女
    2020-11-28 05:51

    Update: September 2019

    It is not possible to use weak references yet, but most likely soon it will be possible, as WeakRefs in JavaScript are Work In Progress. Details below.

    Proposal

    Proposal in now in Stage 3 which means that it has complete specification and that further refinement will require feedback from implementations and users.

    The WeakRef proposal encompasses two major new pieces of functionality:

    • Creating weak references to objects with the WeakRef class
    • Running user-defined finalizers after objects are garbage-collected, with the FinalizationGroup class

    Use cases

    A primary use for weak references is to implement caches or mappings holding large objects, where it’s desired that a large object is not kept alive solely because it appears in a cache or mapping.

    Finalization is the execution of code to clean up after an object that has become unreachable to program execution. User-defined finalizers enable several new use cases, and can help prevent memory leaks when managing resources that the garbage collector doesn't know about.

    Source and further reading

    https://github.com/tc39/proposal-weakrefs
    https://v8.dev/features/weak-references

提交回复
热议问题