WeakSet() 构造函数

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

¥The WeakSet() constructor creates WeakSet objects.

语法

¥Syntax

js
new WeakSet()
new WeakSet(iterable)

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

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

参数

¥Parameters

iterable Optional

如果一个 可迭代对象 被传递,它的所有元素将被添加到新的 WeakSet 中。null 被视为 undefined

示例

¥Examples

使用 WeakSet 对象

¥Using the WeakSet object

js
const ws = new WeakSet();
const foo = {};
const bar = {};

ws.add(foo);
ws.add(bar);

ws.has(foo); // true
ws.has(bar); // true

ws.delete(foo); // removes foo from the set
ws.has(foo); // false, foo has been removed
ws.has(bar); // true, bar is retained

请注意,foo !== bar。虽然它们是相似的对象,但它们不是同一个对象。因此它们都被添加到集合中。

¥Note that foo !== bar. While they are similar objects, they are not the same object. And so they are both added to the set.

规范

Specification
ECMAScript Language Specification
# sec-weakset-constructor

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看