WeakMap() 构造函数
语法
参数
¥Parameters
iterable
-
实现 @@iterator 方法的
Array
或其他可迭代对象,该方法返回迭代器对象,该迭代器对象生成双元素数组状对象,其第一个元素是将用作WeakMap
键的值,第二个元素是要关联的值 用那把钥匙。每个键值对都将添加到新的WeakMap
中。null 被视为未定义。
示例
使用 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 |
浏览器兼容性
BCD tables only load in the browser