--- title: WeakRef slug: Web/JavaScript/Reference/Global_Objects/WeakRef translation_of: Web/JavaScript/Reference/Global_Objects/WeakRef ---
WeakRef对象允许您保留对另一个对象的弱引用,而不会阻止被弱引用对象被GC回收
WeakRef对象包含对对象的弱引用,这个弱引用被称为该WeakRef对象的target或者是referent。对对象的弱引用是指当该对象应该被GC回收时不会阻止GC的回收行为。而与此相反的,一个普通的引用(默认是强引用)会将与之对应的对象保存在内存中。只有当该对象没有任何的强引用时,JavaScript引擎GC才会销毁该对象并且回收该对象所占的内存空间。如果上述情况发生了,那么你就无法通过任何的弱引用来获取该对象。
备注: 在使用前请阅读Avoid where possible,对于WeakRef对象的使用要慎重考虑,能不使用就尽量不要使用
undefined
正确使用WeakRef对象需要仔细的考虑,最好尽量避免使用。避免依赖于规范没有保证的任何特定行为也是十分重要的。何时、如何以及是否发生垃圾回收取决于任何给定JavaScript引擎的实现。GC在一个JavaScript引擎中的行为有可能在另一个JavaScript引擎中的行为大相径庭,或者甚至在同一类引擎,不同版本中GC的行为都有可能有较大的差距。GC目前还是JavaScript引擎实现者不断改进和改进解决方案的一个难题。
以下是WeakRef提案的作者在其解释文件(explainer document)中提出的一些具体观点
Garbage collectors are complicated. If an application or library depends on GC cleaning up a WeakRef 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.
关于WeakRefs的一些说明
WeakRef
s 有相同的目标,那么他们的target对象是一样的。对其中一个调用deref的结果将与对另一个调用deref的结果匹配(在同一个作业中),您不会从其中一个获取目标对象,而是从另一个获取未定义的对象。undefined
这个例子演示了在一个DOM元素中启动一个计数器,当这个元素不存在时停止:
class Counter { constructor(element) { // Remember a weak reference to the DOM element this.ref = new WeakRef(element); this.start(); } start() { if (this.timer) { return; } this.count = 0; const tick = () => { // Get the element from the weak reference, if it still exists const element = this.ref.deref(); if (element) { element.textContent = ++this.count; } else { // The element doesn't exist anymore console.log("The element is gone."); this.stop(); this.ref = null; } }; tick(); this.timer = setInterval(tick, 1000); } stop() { if (this.timer) { clearInterval(this.timer); this.timer = 0; } } } const counter = new Counter(document.getElementById("counter")); counter.start(); setTimeout(() => { document.getElementById("counter").remove(); }, 5000);
规范 |
---|
WeakRefs proposal |
{{Compat("javascript.builtins.WeakRef")}}