[๐ŸŒณ Javascript] ์ƒ์„ฑ์ž ํ•จ์ˆ˜, ํด๋ž˜์Šค

h-a-n-aยท2023๋…„ 5์›” 30์ผ
1

๐ŸŒณjavascript

๋ชฉ๋ก ๋ณด๊ธฐ
5/17

์ƒ์„ฑ์ž ํ•จ์ˆ˜

๊ฐ์ฒด ๋ฆฌํ„ฐ๋Ÿด ๋ฐฉ์‹์„ ์‚ฌ์šฉํ•ด ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•  ์ˆ˜ ์žˆ๋‹ค.

let user = {
  name: 'Mike',
  age: 30,
}

๊ทธ๋Ÿฐ๋ฐ ๋งŒ์•ฝ ๋น„์Šทํ•œ ๊ฐ์ฒด๋ฅผ ์—ฌ๋Ÿฌ ๊ฐœ ๋งŒ๋“ค์–ด์•ผ ํ•˜๋Š” ์ƒํ™ฉ์ด ์˜จ๋‹ค๋ฉด ์œ„์™€ ๊ฐ™์€ ๊ฐ์ฒด๋ฅผ ํ•˜๋“œ์ฝ”๋”ฉํ•ด์•ผ ํ•˜๋Š” ๊ฑธ๊นŒ?
๋‹คํ–‰ํžˆ๋„, ๊ทธ๋Ÿฐ ๊ฒฝ์šฐ์—” ์ƒ์„ฑ์ž ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ๋œ๋‹ค.

// ์ฒซ๊ธ€์ž๋Š” ๋Œ€๋ฌธ์ž๋กœ!
function User(name,age){ 
  this.name = name;
  this.age = age;
}
let user1  = new User('Mike',30)
let user2  = new User('Kitty',20)
let user3  = new User('John',40)
// new ์—ฐ์‚ฐ์ž๋ฅผ ์‚ฌ์šฉํ•ด ํ˜ธ์ถœํ•˜๋ฉด ๋œ๋‹ค.

์ƒ์„ฑ์ž ํ•จ์ˆ˜๋Š” ์‰ฝ๊ฒŒ ์ƒ๊ฐํ•ด ๋ถ•์–ด๋นต ํ‹€์ด๋ผ๊ณ  ์ƒ๊ฐํ•˜๋ฉด ๋œ๋‹ค. ์›ํ•˜๋Š” ์žฌ๋ฃŒ(name,age)๋ฅผ ๋„ฃ๊ณ  ๋น„์Šทํ•œ ๋ชจ์–‘์˜ ๊ฐ์ฒด(User)๋ฅผ ์ƒ์„ฑํ•  ์ˆ˜ ์žˆ๋‹ค.

์œ„ ์˜ˆ์ œ์—์„œ new ์—ฐ์‚ฐ์ž๋ฅผ ์‚ฌ์šฉํ•จ์œผ๋กœ์จ, ์•„๋ž˜์™€ ๊ฐ™์€ ์•Œ๊ณ ๋ฆฌ์ฆ˜ ํ๋ฆ„์œผ๋กœ ๊ฐ์ฒด๊ฐ€ ์ƒ์„ฑ๋œ๋‹ค๊ณ  ์ƒ๊ฐํ•˜๋ฉด ๋œ๋‹ค.

function User(name,age){ 
  // this = {}  <-๋นˆ ๊ฐ์ฒด ์ƒ์„ฑ
  this.name = name;
  this.age = age;
  // ์›ํ•˜๋Š” ์žฌ๋ฃŒ ๋„ฃ์–ด์ง€๊ณ 
  // return this; <-๋ถ•์–ด๋นต ๋Œ๋ ค๋ฐ›์Œ
}

๋งŒ์•ฝ์— new ๋ฅผ ๋ถ™์—ฌ์ฃผ์ง€ ์•Š๊ณ  let user2= User('Kitty',20) ๋ผ๊ณ ๋งŒ ์‹คํ–‰ํ•œ๋‹ค๋ฉด
์œ„ ์ƒ์„ฑ์ž ํ•จ์ˆ˜ ์‹คํ–‰์—์„œ ๋”ฐ๋กœ returnํ•˜๋Š” ๊ฐ’์€ ์—†์œผ๋‹ˆ undefined๊ฐ€ ์ถœ๋ ฅ๋  ๊ฒƒ์ด๋‹ค.

ํด๋ž˜์Šค

์šฐ๋ฆฌ๊ฐ€ ์œ„์—์„œ ์‚ฌ์šฉํ•ด๋ณธ ์ƒ์„ฑ์ž ํ•จ์ˆ˜๋Š” ์•„๋ž˜์™€ ๊ฐ™๋‹ค.

function User(name,age){ 
  this.name = name;
  this.age = age;
  this.showName = function(){
    console.log(this.name)
  }
}

const mike = new User('mike',30)

์ด์ œ ์ƒˆ๋กญ๊ฒŒ ๋“ฑ์žฅํ•œ ํด๋ž˜์Šค ํ•จ์ˆ˜๋ฅผ ์‚ดํŽด๋ณด์ž.

class User2{
  constructor(name,age){
    this.name = name;
    this.age = age;
  }
  showName(){
    console.log(this.name);
  }
}

const tom = new User2('tom',23)

์œ„์—์„œ ๋ณด๋‹ค์‹œํ”ผ class ๋ผ๋Š” ํ‚ค์›Œ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜๋ฉฐ, ๋‚ด๋ถ€์—๋Š” constructor๋ผ๋Š” ๋ฉ”์†Œ๋“œ๊ฐ€ ์‚ฌ์šฉ๋œ๋‹ค.

constructor๋Š” ๊ฐ์ฒด๋ฅผ ๋งŒ๋“ค์–ด์ฃผ๋Š” ์ƒ์„ฑ์ž method ์ด๋‹ค. ๊ฐ์ฒด๋ฅผ ์ดˆ๊ธฐํ™”ํ•˜๊ธฐ ์œ„ํ•œ ๊ฐ’์„ constructor ๋‚ด๋ถ€์— ์‚ฌ์šฉํ•˜๊ณ , ์ƒ์„ฑ์ž ํ•จ์ˆ˜๋•Œ์™€ ๋งˆ์ฐฌ๊ฐ€์ง€๋กœ new ์—ฐ์‚ฐ์ž๋ฅผ ํ†ตํ•ด ํ˜ธ์ถœํ•˜๋ฉด ๋œ๋‹ค.

๊ทธ๋ ‡๋‹ค๋ฉด ์ผ๋ฐ˜ ์ƒ์„ฑ์ž ํ•จ์ˆ˜์™€ class ์˜ ์ฐจ์ด๋Š” ๋ฌด์—‡์ผ๊นŒ?
๊ทธ ์ฐจ์ด๋ฅผ ์•Œ๊ธฐ ์œ„ํ•ด ์ด ๋‘˜๋กœ ๋งŒ๋“  ๊ฐ์ฒด๋ฅผ ๊ฐ๊ฐ ํ˜ธ์ถœํ•ด๋ณด์ž.

tom์€ prototype ๋‚ด๋ถ€์— showName์ด ๋“ค์–ด๊ฐ€๊ณ , mike๋Š” ๊ฐ์ฒด ๋‚ด๋ถ€์— showName์ด ์กด์žฌํ•œ๋‹ค.
๋˜ํ•œ tom์€ class ์ด๋ฏ€๋กœ new ํ‚ค์›Œ๋“œ ์—†์ด ํ˜ธ์ถœํ•˜๋ฉด ์—๋Ÿฌ๊ฐ€ ๋‚œ๋‹ค.(mike๋Š” ์—๋Ÿฌ๋Š” ์•ˆ๋‚จ)

for in ๋ฌธ์„ ์‚ฌ์šฉํ•ด๋ณด๋ฉด prototype์— ํฌํ•จ๋œ property๋ฅผ ๋‹ค ๋ณด์—ฌ์ฃผ๊ณ , ๊ฐ์ฒด๋งŒ ๊ฐ€์ง„ property๋ฅผ ํŒ๋ณ„ํ•˜๊ธฐ ์œ„ํ•ด์„œ hasOwnProperty ๋ฅผ ์‚ฌ์šฉํ•ด์•ผ ํ–ˆ๋‹ค. class์˜ ๋ฉ”์†Œ๋“œ๋Š” for in ๋ฌธ์—์„œ ์ œ์™ธ๋œ๋‹ค.

์ƒ์†

extends ํ‚ค์›Œ๋“œ๋ฅผ ์‚ฌ์šฉํ•ด ๊ตฌํ˜„ํ•œ๋‹ค.

profile
ํ•˜๋ฃจํ•˜๋ฃจ๊ฐ€ ์—ฐ์Šต์ด๋‹ˆ ๋‚ด์ผ์€ ๋” ๊ฐ•ํ•ด์งˆ ๊ฒ๋‹ˆ๋‹ค

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