๐Ÿ“’Javascript ์‹ฌ๋ณผ :)

zooyahoยท2022๋…„ 4์›” 7์ผ
0

study with me

๋ชฉ๋ก ๋ณด๊ธฐ
7/19
post-thumbnail

Symbol

  • Symbolํ•จ์ˆ˜๋ฅผ ํ˜ธ์ถœํ•˜์—ฌ ์ƒ์„ฑํ•จ.
  • ์œ ์ผํ•œ ์‹๋ณ„์ž๋ฅผ ๋งŒ๋“ค๊ธฐ ์œ„ํ•ด ์‚ฌ์šฉ
  • ์ธ์ˆ˜๋กœ ํ•ด๋‹น ์‹๋ณ„์ž์˜ ์„ค๋ช…์„ ๋ถ€์—ฌํ•  ์ˆ˜ ์žˆ์Œ.
  • ์„ ํƒ์ ์œผ๋กœ ๋ฌธ์ž์—ด์„ ์ธ์ˆ˜๋กœ ์ „๋‹ฌํ•  ์ˆ˜ ์žˆ์Œ. ์ด ๋ฌธ์ž์—ด์€ ์‹ฌ๋ฒŒ ๊ฐ’์— ๋Œ€ํ•œ ์„ค๋ช…์œผ๋กœ ๋””๋ฒ„๊น… ์šฉ๋„๋กœ ์‚ฌ์šฉํ•จ~!, ์‹ฌ๋ฒŒ ๊ฐ’์— ๋Œ€ํ•œ ์„ค๋ช…์ด ๊ฐ™๋”๋ผ๋„ ๊ฐ’์€ ์œ ์ผ๋ฌด์ดํ•œ ๊ฐ’์ž„!!!
  • ์•”๋ฌต์ ์œผ๋กœ ๋ฌธ์ž์—ด๊ณผ ์ˆซ์ž๋กœ ํƒ€์ž…๋ณ€ํ•˜์ง€ ์•Š์œผ๋ฉฐ ๋ถˆ๋ฆฌ์–ธ ํƒ€์ž…์œผ๋กœ๋Š” ์•”๋ฌต์  ํƒ€์ž… ๋ณ€ํ™˜๋œ๋‹ค.

๐Ÿ‘พ #1

const a = Symbol(); // new๋ฅผ ๋ถ™์ด์ง€ ์•Š์Œ

/* ์œ ์ผํ•œ ์‹๋ณ„์ž */
const a = Symbol();
const b = Symbol();

console.log(a === b) // false
console.log(a == b) // false

๐Ÿ‘พ #2 property key:์‹ฌ๋ณผํ˜•

const id = Symbol('id');
const user = {
  name: 'Mike',
  [id] : 'myid'
}
console.log(user); // {name: 'Mike', Symbol(id): 'myid'}

๐Ÿ‘‰๐Ÿป Object.keys(user), Object.values(user), Object.entries(user), for(let a in user){} ๋ชจ๋‘ ์‹ฌ๋ณผํ˜•์€ ๊ฑด๋„ˆ๋›ฐ๊ณ  ์‹คํ–‰ํ•จ!!

๐Ÿ“Œ Symbol ์‚ฌ์šฉ ์˜ˆ์ œ

๐Ÿ‘พ #1 symbol ์‚ฌ์šฉX

// ๋‹ค๋ฅธ ๊ฐœ๋ฐœ์ž๊ฐ€ ๋งŒ๋“ค์–ด ๋†“์€ ๊ฐ์ฒด
const user = {
  name: 'Zooyaho',
  age: 34,
}

// ๋‚ด๊ฐ€ ์ž‘์—…
user.showName = function() {}

// ์‚ฌ์šฉ์ž๊ฐ€ ์ ‘์†ํ•˜๋ฉด ๋ณด๋Š” ๋ฉ”์„ธ์ง€
for( let key in user) {
  console.log(`His ${key} is ${user[key]}.`);
}

๐Ÿ“console

๐Ÿ‘พ #2 symbol ์‚ฌ์šฉ

// ๋‹ค๋ฅธ ๊ฐœ๋ฐœ์ž๊ฐ€ ๋งŒ๋“ค์–ด ๋†“์€ ๊ฐ์ฒด
const user = {
  name: 'Zooyaho',
  age: 34,
}

// ๋‚ด๊ฐ€ ์ž‘์—…
const showName = Symbol("show name");
user[showName] = function() {
  console.log(this.name);
}

// ์‚ฌ์šฉ์ž๊ฐ€ ์ ‘์†ํ•˜๋ฉด ๋ณด๋Š” ๋ฉ”์„ธ์ง€
for( let key in user) {
  console.log(`His ${key} is ${user[key]}.`);
}

๐Ÿ“console

๐Ÿ“Œ ์ˆจ๊ฒจ์ง„ Symbol key ๋ณด๋Š”๋ฒ•

  • Object.getOwnPropertySymbols(๊ฐ์ฒด);
  • Reflect.ownKeys(๊ฐ์ฒด);

๐Ÿ”ต Symbol.for()

  • ์ „์—ญ ์‹ฌ๋ณผ
  • ์—†์œผ๋ฉด ๋งŒ๋“ค๊ณ , ์žˆ์œผ๋ฉด ๊ฐ€์ ธ์˜ค๊ธฐ ๋•Œ๋ฌธ์— ํ•˜๋‚˜์˜ ์‹ฌ๋ณผ๋งŒ ๋ณด์žฅ๋ฐ›์„ ์ˆ˜ ์žˆ์Œ.
  • Symbol ํ•จ์ˆ˜๋Š” ๋งค๋ฒˆ ๋‹ค๋ฅธ Symbol ๊ฐ’์„ ์ƒ์„ฑํ•˜์ง€๋งŒ, Symbol.for ๋ฉ”์†Œ๋“œ๋Š” ํ•˜๋‚˜๋ฅผ ์ƒ์„ฑํ•œ ๋’ค ํ‚ค๋ฅผ ํ†ตํ•ด ๊ฐ™์€ Symbol์„ ๊ณต์œ ํ•จ.
const idA = Symbol.for('id');
const idB = Symbol.for('id');

console.log(idA === idB) // true

๐Ÿ”ต Symbol.keyFor()

  • Symbol.keyFor(๋ณ€์ˆ˜)
  • ํ•ด๋‹น ๋ณ€์ˆ˜์˜ symbol key๊ฐ’์„ ์•Œ ์ˆ˜ ์žˆ์Œ.
const idA = Symbol.for('id');
console.log(Symbol.keyFor(idA)); // 'id'

๐Ÿ”ต description

  • ์ „์—ญ ์‹ฌ๋ณผ์ด ์•„๋‹Œ ์‹ฌ๋ณผ์€ keyFor()์„ ์‚ฌ์šฉํ•  ์ˆ˜ ์—†์Œ.
const id = Symbol('id ์ž…๋‹ˆ๋‹ค.');
console.log(id.description); // 'id ์ž…๋‹ˆ๋‹ค.'
profile
์ฆ๊ฒ๊ฒŒ ๊ฐœ๋ฐœํ•˜์ž ์ฅฌ์•ผํ˜ธ๐Ÿ‘ป

0๊ฐœ์˜ ๋Œ“๊ธ€