Symbol
Symbol 심벌 <- 유일한 key, 유일한 value를 나타낼 때 유용하다.
유일한 키를 생성할 수 있음 🔑
const map1 = new Map();
const key1 = "key";
const key2 = "key";
map1.set(key1, "Hello");
console.log(map1.get(key2));
console.log(key1 === key2); // true
const map2 = new Map();
const key3 = Symbol("key");
const key4 = Symbol("key");
map2.set(key3, "Hello");
console.log(map2.get(key4));
console.log(key3 === key4); // false
// 동일한 이름으로 하나의 키를 사용하고 싶다면, Symbol.for
// 전역 심벌 레지스트리 (Global Symbol Registry)
const k1 = Symbol.for("key");
const k2 = Symbol.for("key");
console.log(k1 === k2);
// keyFor은 전역 심벌 레지스트리에 보관된 symboldp 한정해서 작동됨
console.log(Symbol.keyFor(k1)); // key
console.log(Symbol.keyFor(key1)); // undefined
const obj = { [k1]: "Hello", [Symbol("key")]: 1 };
console.log(obj);
console.log(obj[k1]);
console.log(obj[Symbol("key")]);
'자바스크립트 개념정리' 카테고리의 다른 글
이벤트(Event), 이벤트의 종류, 이벤트 연결 (0) | 2022.12.09 |
---|---|
DOM 정리 (0) | 2022.12.06 |
Set&Map (0) | 2022.12.04 |
Iterator&Generator (0) | 2022.12.02 |
자료구조(data structure) (0) | 2022.11.29 |