[๊ฐ์ฒด์ง€ํ–ฅ]class/class extends/super()

ํŠธ๋ฆด๋กœ๋‹ˆยท2021๋…„ 11์›” 25์ผ

์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ

๋ชฉ๋ก ๋ณด๊ธฐ
9/31

class

class Person{
  constructor(name, first, second){
    this.name = name;
    this.first = first;
    this.second = second;
  }
  sum(){
    return this.first + this.second
  }
}
let kim = new Person('kim', 10, 20);
kim.sum = function(){
  return this.first * this.second
}
console.log(kim)
console.log(kim.sum())

๐Ÿ“Œ constructor(){}

  • ๊ฐ์ฒด์˜ ์ดˆ๊ธฐ ์ƒํƒœ๋ฅผ ์„ธํŒ…ํ•˜๋Š” ํ•จ์ˆ˜
  • class๋กœ ๊ฐ์ฒด๋ฅผ ๋งŒ๋“ค๋ฉด constructor๋Š” ์ž๋™์ ์œผ๋กœ ์‹คํ–‰๋œ๋‹ค.

๐Ÿ“Œ class์—์„œ ๋ฉ”์„œ๋“œ

  • sum(){}๊ฐ™์ด function์„ ์ƒ๋žตํ•˜๊ณ  ์„ ์–ธ

class extends

class Person{
  constructor(name, first, second){
    this.name = name;
    this.first = first;
    this.second = second;
  }
  sum(){
    return this.first + this.second
  }
}

class PersonPlus extends Person {
  avg(){
    return (this.first+this.second)/2;
  }
}

let kim = new PersonPlus('kim', 10 ,20)

console.log(kim.sum())
console.log(kim.avg())

๐Ÿ“Œ class PersonPlus extends Person{}

  • PersonPlus class์— Person class๊ฐ€ ์ƒ์†๋จ
  • ๋ถ€๋ชจclass์˜ ์†์„ฑ์ด ์ˆ˜์ •๋˜๋ฉด ์ž์‹ class๋กœ ์ˆ˜์ •๋จ

โ–ช ์ƒ์†์€ ์™œ ํ•„์š”ํ•  ๊นŒ?

  • ๋ถ€๋ชจ์ฝ”๋“œ๋ฅผ ๊ธฐ๋ฐ˜์œผ๋กœ ์ถ”๊ฐ€ํ•ด์ฃผ๊ณ  ์‹ถ์€ ๋ฉ”์„œ๋“œ๊ฐ€ ์žˆ์„ ๋•Œ ์ฝ”๋“œ ์ค‘๋ณต์—†์ด ํ•  ์ˆ˜ ์žˆ์Œ
  • ๋ถ€๋ชจ class๋ฅผ ์ง์ ‘ ์ˆ˜์ •ํ•˜์ง€ ์•Š๊ณ  ์ƒ์†๋ฐ›์•„์„œ ์ƒˆ๋กœ์šด class๋ฅผ ๋งŒ๋“œ๋Š” ๊ฒƒ์ด๊ธฐ ๋•Œ๋ฌธ์—
    ์œ ์ง€๋ณด์ˆ˜๊ฐ€ ํŽธ๋ฆฌํ•จ

super

class Person{
  constructor(name, first, second){
    this.name = name;
    this.first = first;
    this.second = second;
  }
  sum(){
    return this.first + this.second
  }
}
class PersonPlus extends Person {
  constructor(name, first, second, third){
    super(name, first, second);
    this.third = third;
  }
  sum(){
    return super.sum()+this.third;
  }
  avg(){
    return ( this.first+this.second+this.third )/3;
  }
}

let kim = new PersonPlus('kim', 10 ,20, 30) 

console.log(kim.sum())
console.log(kim.avg())

๐Ÿ“Œsuper(): ๋ถ€๋ชจ class์˜ ์ƒ์„ฑ์ž(constructor)๋ฅผ ํ˜ธ์ถœ

  • person์˜ constructor ์ธ์ž๋Š” ์›ํ˜• ๊ทธ๋Œ€๋กœ ๋‘๊ณ  personPlus์˜ constructor์— person์˜ constructor๋ฅผ ์ƒ์†๋ฐ›๊ณ  ๋‹ค๋ฅธ ์ธ์ž๋ฅผ ์ถ”๊ฐ€ํ•˜๊ณ  ์‹ถ์„ ๋•Œ

๐Ÿ“Œsuper. : ๋ถ€๋ชจํด๋ž˜์Šค์˜ ๋ฉ”์„œ๋“œ ํ˜ธ์ถœ

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