프론트엔드/자바스크립트

Inheritance

테오구 2022. 3. 31. 22:21
728x90

Inheritance (상속)

  • 부모 class에 있는 모든 것들이 자식 class에 포함이 됨
  • 공통되어지는 값들을 extends 키워드로 재사용 할 수 있다
  • 부모 class의 값을 변경하면 자식(상속 받은) class의 값들도 자동으로 변경됨

부모의 constructor가 2개일 때

class Animal {
  constructor(color,eat) {
    this.color = color
    this.eat = eat
  }
  eat() {
    console.log('먹자!')
  }
  sleep() {
    console.log('잔다')
  }
}

class Dog extends Animal {
  constructor(color,eat ,ownerName) {
    super(color, eat)
    
    this.ownerName = ownerName
  }
  play() {
    console.log('놀자')
  }
  
}
const dog = new Dog('빨강이','고기' ,'승빈')

console.log(dog)
class Animal {
  constructor(color) {
    this.color = color
  }
  eat() {
    console.log('먹자!')
  }
  sleep() {
    console.log('잔다')
  }
}
// 아무것도 작성해주지 않아도 Animal이 적용된다.
class Tiger extends Animal {}

const tiger = new Tiger('노랑이')
console.log(tiger)

class Dog extends Animal {
  constructor(color, ownerName) {
    super(color)
    this.ownerName = ownerName
  }
  play() {
    console.log('놀자')
  }
  eat() {
    // 부모의 기능을 그대로 유지하면서 추가적인 행동을 하고 싶다면
    super.eat()
    console.log('강아지가 먹는다.')
  }
}
const dog = new Dog('빨강이', '승빈')

console.log(dog)
class Counter {
  #number
  constructor(startValue) {
    if(isNaN(startValue) || startValue < 0){
      this.#number = 0
    }else{
      this.#number = startValue
      
    }
  }
  
  get value(){
    return this.#number
  }
  
  up(){
    this.#number++
  }
}

const counter = new Counter(0)
counter.up()
console.log(counter.value)
class Employee {
  constructor(name, department, time) {
    this.name = name
    this.department = department
    this.time = time
  }
}

class FullTimeEmployee extends Employee{
  #payRate = 10000
  constructor(name, department, time){
    super(name, department, time)
    
  }
  get pay(){
    return this.#payRate * this.time
  }
}

class PartTimeEmployee extends Employee{
  #payRate = 8000
  constructor(name, department, time){
    super(name, department, time)
    
  }
  get pay(){
    return this.#payRate * this.time
  }
}

const fullTimeEmployee = new FullTimeEmployee('승빈', '개발부', 2)
const partTimeEmployee = new PartTimeEmployee('승빈', '개발부', 2)

console.log(fullTimeEmployee.pay)
console.log(partTimeEmployee.pay)
728x90

'프론트엔드 > 자바스크립트' 카테고리의 다른 글

제너레이터  (0) 2022.04.20
이터러블  (0) 2022.04.04
Getter & Setter  (0) 2022.03.30
논리 연산자  (0) 2021.10.15
foreach, for in, for of  (0) 2021.10.09