WeakRef弱引用
顾名思义,弱引用意味着弱关联,如果被引用对像被回收,WeakRef可以被感知
// 这个例子演示了在一个DOM元素中启动一个计数器,当这个元素不存在时停止
// 相对,如果不使用 WeakRef弱引用 元素不在时不能被程序感知
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);
与之相对的还有一个叫 FinallizationReginstry 的对象,可以针对引用注册一个回调,当引用被删除时触发 可以做些清理事项
const registry = new FinalizationRegistry((heldValue) => {
// 这里做清理
console.log(heldValue);
});
(function(){
const demo = document.getElementById("s");
registry.register(demo, "demo 对象已被回收.");
})()
setTimeout(() => {
document.getElementById("s").remove();
}, 2000);