[ Web Proxy ]
URL:
Viewing: https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/WeakRef [Back]  [Original]

WeakRef - JavaScript | MDN

MDN Web Docs

View in English Always switch to English

WeakRef

Baseline *

20214

*

WeakRef

WeakRef JavaScript

WeakRef

WeakRef JavaScript JavaScript

WeakRef

WeakRef

  • JavaScript
  • JavaScript
  • API

WeakRef

  • WeakRef WeakRef deref JavaScript JavaScript JavaScript
  • WeakRef 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

WeakRef

DOM

js
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