WeakMap() 构造函数

WeakMap() 构造函数创建 WeakMap 对象。

¥The WeakMap() constructor creates WeakMap objects.

语法

¥Syntax

js
new WeakMap()
new WeakMap(iterable)

注意:WeakMap() 只能与 new 一起构建。尝试在没有 new 的情况下调用它会抛出 TypeError

¥Note: WeakMap() can only be constructed with new. Attempting to call it without new throws a TypeError.

参数

¥Parameters

iterable

实现 @@iterator 方法的 Array 或其他可迭代对象,该方法返回迭代器对象,该迭代器对象生成双元素数组状对象,其第一个元素是将用作 WeakMap 键的值,第二个元素是要关联的值 用那把钥匙。每个键值对都将添加到新的 WeakMap 中。null 被视为未定义。

示例

¥Examples

使用 WeakMap

¥Using WeakMap

js
const wm1 = new WeakMap();
const wm2 = new WeakMap();
const wm3 = new WeakMap();
const o1 = {};
const o2 = function () {};
const o3 = window;

wm1.set(o1, 37);
wm1.set(o2, "azerty");
wm2.set(o1, o2); // a value can be anything, including an object or a function
wm2.set(o3, undefined);
wm2.set(wm1, wm2); // keys and values can be any objects. Even WeakMaps!

wm1.get(o2); // "azerty"
wm2.get(o2); // undefined, because there is no key for o2 on wm2
wm2.get(o3); // undefined, because that is the set value

wm1.has(o2); // true
wm2.has(o2); // false
wm2.has(o3); // true (even if the value itself is 'undefined')

wm3.set(o1, 37);
wm3.get(o1); // 37

wm1.has(o1); // true
wm1.delete(o1);
wm1.has(o1); // false

规范

Specification
ECMAScript Language Specification
# sec-weakmap-constructor

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看