심볼은 유일성을 갖는다. 아래와 같이 같은 값을 넣었지만 서로 동일하지 않다고 나온다.
const id1 = Symbol('id');
const id2 = Symbol('id');
console.log(id1===id2)
심볼은 객체내에서 for in 반복문이나 Object.keys와 같은 메소드로는 나오지 않는다.
심볼의 사용성은 다른사람이 만든코드에 내가 코드를 추가할 때 사용될 수 있다.
const user = {
name:'Mike',
age:30,
showname(){
console.log("Mike입니다.");
}
}
user.showname();
const showname = Symbol("Show Name");
user[showname]=function() {
console.log("Mike가 바뀌었습니다.");
}
user[showname]();
Symbol은 user[property]
로 접근할 수 있지만, user.property
로는 접근할 수 없다.
전역심볼은 동일한 심볼을 나타낼 때 사용된다. 위의 코드에서는 False가 나왔지만 아래는 True가 나온다.
const id1 = Symbol.for('id');
const id2 = Symbol.for('id');
console.log(id1===id2)