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

前端 未结 9 1735
忘掉有多难
忘掉有多难 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:54

    Using a caching mechanism to emulate a weak reference, as JL235 suggested above, is reasonable. If weak references would exist natively, you would observe a behavior like this:

    this.val = {};
    this.ref = new WeakReference(this.val);
    ...
    this.ref.get(); // always returns val
    ...
    this.val = null; // no more references
    ...
    this.ref.get(); // may still return val, depending on already gc'd or not
    

    Whereas with a cache you would observe:

    this.val = {};
    this.key = cache.put(this.val);
    ...
    cache.get(this.key); // returns val, until evicted by other cache puts
    ...
    this.val = null; // no more references
    ...
    cache.get(this.key); // returns val, until evicted by other cache puts
    

    As a holder of a reference, you should not make any assumptions about when it refers to a value, this is no different using a cache

提交回复
热议问题