WeakRef() 构造函数

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since April 2021.

WeakRef() 会创建一个 WeakRef 对象,它是对于目标对象的弱引用。

语法

js
new WeakRef(targetObject)

备注: WeakRef() 必须通过 new 关键字调用。试图在没有 new 的情况下调用会抛出一个 TypeError

参数

targetObject

WeakRef 要指向的目标对象 (也称作 referent)。

示例

创建一个新的 WeakRef 对象

完整的示例请见 WeakRef 主页面。

js
class Counter {
  constructor(element) {
    // 创建一个对 DOM 元素的弱引用
    this.ref = new WeakRef(element);
    this.start();
  }
}

规范

Specification
ECMAScript® 2025 Language Specification
# sec-weak-ref-constructor

浏览器兼容性

Report problems with this compatibility data on GitHub
desktopmobileserver
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
Deno
Node.js
WeakRef() constructor

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support

参见