此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。

View in English Always switch to English

WeakRef.prototype.deref()

基线 广泛可用

自 2021年4月 起,此特性已在主流浏览器中得到支持,可在大多数设备和浏览器版本中正常使用。

deref方法返回WeakRef 实例的目标对象,如果目标对象已被垃圾收集,则返回undefined

语法

obj = ref.deref();

返回值

返回 WeakRef 的目标对象,如果该对象已被垃圾收集,则返回undefined

说明

有关一些重要说明,请参阅WeakRef页面上的Notes on WeakRefs

示例

使用 deref

有关完整示例,请参阅WeakRef页面的示例部分。

js
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;
  }
};

规范

规范
ECMAScript® 2027 Language Specification
# sec-weak-ref.prototype.deref

浏览器兼容性

参见