[Javascript] Object_Symbol Type

Suyeon·2020년 8월 24일
0

Javascript

목록 보기
5/31
  • Symbol is a primitive data type of JavaScript.(ES6)
  • A “symbol” represents a unique identifier.

Example

let id1 = Symbol("id");
let id2 = Symbol("id");

alert(id1 == id2); // false

// Symbols don’t auto-convert to a string
let id = Symbol("id");
alert(id.toString());

✔️ "id1" is a new symbol and "id" is a description(Symbol name). Symbol description is mostly useful for debugging purposes.

✔️ Symbols are skipped by for…in and Object.keys(user) but not Object.assign()

Global Symbol

  • When we want same-named symbols to be same entities.
// get symbol by name
let sym = Symbol.for("name"); // if the symbol did not exist, it is created
let sym2 = Symbol.for("id");

alert( sym === sym2 ); // the same symbol: true

// get name by symbol
alert( Symbol.keyFor(sym) ); // name
alert( Symbol.keyFor(sym2) ); // id
profile
Hello World.

0개의 댓글