| [ Web Proxy ] |
| Viewing: https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/WeakRef | [Back] [Original] |
Get to know MDN better
WeakRef JavaScript
WeakRef JavaScript JavaScript
- JavaScript
- JavaScript
- API
WeakRef WeakRef deref JavaScript JavaScript JavaScriptWeakRef deref deref WeakRef FinalizationRegistry WeakRef WeakRef undefined WeakRef deref undefined WeakRef() WeakRef
WeakRef.prototype WeakRef
WeakRef.prototype.constructor WeakRef WeakRef
:
"normative optional" constructor WeakRef
WeakRef.prototype[Symbol.toStringTag]@@toStringTag "WeakRef" Object.prototype.toString()
WeakRef.prototype.deref()WeakRef 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"));
setTimeout(() => {
document.getElementById("counter").remove();
}, 5000);
| ECMAScript 2027 LanguageSpecification # sec-weak-ref-objects |
| Web Proxy Viewer | New URL | Original Page |