
Symbol은 원시타입중에 하나로 유일한 키를 생성할 때 사용한다.
Symbol은 생성자 함수로 생성한다. 그러나 new 연산자는 사용하지 않는다.
const blackBear = Symbol("bear");
const whiteBear = Symbol("bear");
console.log(blackBear===whiteBear); // false
const map =new Map();
map.set(blackBear,"Big"); // value값 Big으로 설정
console.log(map.get(blackBear)); // Big
console.log(map.get(whiteBear)); // undefined
인자로 전달받은 키를 Symbol값들이 저장되어있는 전역 심볼 레지스트리에서 해당 키와 일치하는 저장된 Symbol값을 검색한다.
const blackBear2= Symbol.for('bear');
// Symbol registry에 key라는 이름을 가진 키를 가져오고 없다면 생성
const whiteBear2= Symbol.for('bear');
// Symbol registry에서 key라는 이름이 있으므로 그 키 를 가져와 사용
console.log(blackBear2===whiteBear2); // true
Symbol은 코드내 보안을 주고 싶을 때 사용할 수 있다.
const blackBear2= Symbol.for('bear');
const whiteBear2= Symbol.for('bear');
const obj ={
[blackBear2] : "Big",
[Symbol('bear')]: "small" // 보안을 주기위해 사용
}
console.log(obj); // { [Symbol(bear)]: 'Big', [Symbol(bear)]: 'small' }
console.log(obj[blackBear2]); // Big
console.log(obj[whiteBear2]); // Big , registry에서 같은 키 공유
console.log(obj[Symbol('bear')]); // undefined
//obj안의 [Symbol('key')]과 출력하고자 하는 [Symbol('key')]는 전혀 다른 키이므로
심볼이 가진 키(문자열) 정보를 출력한다.
const blackBear= Symbol.for('bear');
const whiteBear= Symbol.for('bear');
console.log(Symbol.keyFor(blackBear)); // bear