This page was translated from English by the community. Learn more and join the MDN Web Docs community.

View in English Always switch to English

WeakSet.prototype.add()

Baseline Widely available

This feature is well established and works across many devices and browser versions. Itโ€™s been available across browsers since โจ2015๋…„ 9์›”โฉ.

WeakSet ์ธ์Šคํ„ด์Šค์˜ add() ๋ฉ”์„œ๋“œ๋Š” ์ด WeakSet์˜ ๋์— ์ƒˆ๋กœ์šด ๊ฐ์ฒด๋ฅผ ์ถ”๊ฐ€ํ•ฉ๋‹ˆ๋‹ค.

์‹œ๋„ํ•ด ๋ณด๊ธฐ

const weakset1 = new WeakSet();
const object1 = {};

weakset1.add(object1);
console.log(weakset1.has(object1));
// Expected output: true

try {
  weakset1.add(1);
} catch (error) {
  console.log(error);
  // Expected output (Chrome): TypeError: Invalid value used in weak set
  // Expected output (Firefox): TypeError: WeakSet value must be an object, got 1
  // Expected output (Safari): TypeError: Attempted to add a non-object key to a WeakSet
}

๊ตฌ๋ฌธ

js
add(value)

๋งค๊ฐœ๋ณ€์ˆ˜

value

๋ฐ˜๋“œ์‹œ ๊ฐ์ฒด์ด๊ฑฐ๋‚˜ ๋“ฑ๋ก๋˜์ง€ ์•Š์€ ์‹ฌ๋ณผ์ด์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. WeakSet ์ปฌ๋ ‰์…˜์— ์ถ”๊ฐ€๋  ๊ฐ’์ž…๋‹ˆ๋‹ค.

๋ฐ˜ํ™˜ ๊ฐ’

WeakSet ๊ฐ์ฒด.

์˜ˆ์™ธ

TypeError

value๊ฐ€ ๊ฐ์ฒด๊ฐ€ ์•„๋‹ˆ๊ฑฐ๋‚˜ ๋“ฑ๋ก๋˜์ง€ ์•Š์€ ์‹ฌ๋ณผ์ผ ๊ฒฝ์šฐ ๋ฐœ์ƒํ•ฉ๋‹ˆ๋‹ค.

์˜ˆ์ œ

add ์‚ฌ์šฉํ•˜๊ธฐ

js
const ws = new WeakSet();

ws.add(window); // window ๊ฐ์ฒด๋ฅผ WeakSet์— ์ถ”๊ฐ€

ws.has(window); // true

// WeakSet๋Š” ์ธ์ˆ˜๋กœ ์˜ค์ง ๊ฐ์ฒด๋งŒ ๋ฐ›์Šต๋‹ˆ๋‹ค
ws.add(1);
// Chrome ์—์„œ๋Š” "TypeError: Invalid value used in weak set"๋ผ๋Š” ๊ฒฐ๊ณผ๊ฐ€,
// Firefox ์—์„œ๋Š” "TypeError: 1 is not a non-null object" ๋ผ๋Š” ๊ฒฐ๊ณผ๊ฐ€ ๋‚˜์˜ต๋‹ˆ๋‹ค

๋ช…์„ธ์„œ

Specification
ECMAScriptยฎ 2026 Language Specification
# sec-weakset.prototype.add

๋ธŒ๋ผ์šฐ์ € ํ˜ธํ™˜์„ฑ

๊ฐ™์ด ๋ณด๊ธฐ