코로 넘어져도 헤딩만 하면 그만

Bees (프로토타입 체인 과제 해설) 본문

CODE STATES 44

Bees (프로토타입 체인 과제 해설)

꼬드리 2023. 3. 16. 17:42
class Grub {
  constructor(age, color, food, eat) {
    this.age = 0;
    this.color = "pink";
    this.food = "jelly";
  }
  eat() {
    return `Mmmmmmmmm jelly`;
  }
  //메소드는 constructor {} 안에 쓰지 않도록 주의할 것.
}

//아래가 정석 레퍼런스. constructor 내부에만 상세 요소를 넣어준 걸 볼 수 있다.
//이게 더 재활용성이 높은 코드
class Grub {
  constructor(age = 0, color = 'pink', food = 'jelly') {
    this.age = age;
    this.color = color;
    this.food = food;
  }

  eat() {
    return `Mmmmmmmmm jelly`;
  }
}

Grub 애벌레 클래스. ES6문법으로 작성된 클래스로, 다른 클래스들보다 가장 높은 상단에 위치한다. age, color, food를 속성으로, eat를 메소드로 갖는 게 특징이다. 

eat() 과 같은 메소드는 constructor 내부에 쓰지 않도록 조심한다. 

 

class Bee extends Grub {
  constructor(age, color, food, eat) {
    super(age, color, food, eat);
    this.age = 5;
    this.color = "yellow";
    this.job = "Keep on growing";
  }
}

//아래가 레퍼런스.
class Bee extends Grub {
  constructor(age = 5, color = 'yellow', food, job = 'Keep on growing') {
    super(age, color, food)
    this.job = job
  }
}

이제 Grub를 부모 클래스로 둔 Bee클래스를 만들어주었다.

Bee는 Grub의 age, color, food, eat를 그대로 받아온다. super()에 넣어주면 부모의 속성을 쏙 받아올 수 있다! 받아온 age는 5로, color은 yellow로 바꿔준 뒤 아래에 job라고 새로운 속성을 하나 더 부여해준다. job은 Grub에는 없던 속성이되 Bee에서만 새로 생긴 것이다! 

(애벌레가 자라서 다 자란 벌이 되었으니 이제 일을 할 수 있으니까~)

 

Bee를 부모 클래스로 두는 자식 클래스, ForagerBee를 만들어보자.

class ForagerBee extends Bee {
  constructor(age, color, food, eat, job) {
    super(age, color, food, eat, job);
    this.age = 10;
    this.job = "find pollen";
    this.canFly = true;
    this.treasureChest = [];
  }
  forage(treasure) {
    this.treasureChest.push(treasure);
  }
  //treasure를 매개변수로 하나 넣어줘야 한다.
}

//아래가 정석 레퍼런스
class ForagerBee extends Bee {
  constructor(age = 10, color, food, job = 'find pollen', canFly = true) {
    super(age, color, food, job);
    this.canFly = canFly;
    this.treasureChest = [];
  }

  forage(treasure) {
    return this.treasureChest.push(treasure);
  }
}

forage라는 메소드를 새롭게 가지면서 treasureChest라는 배열 내부에 자신이 수확한 보물들을 밀어넣는 업무를 담당한다. 또한 canFly를 true로 가지고, age와 job은 바뀌었다는 것을 볼 수 있다. 이처럼 부모에게서 상속받은 것들이 일부 있되 자식에서도 자유롭게 추가 및 변용할 수 있다.

Bee 클래스들을 만들며 어떻게 프로토타입 체인이 돌아가고 Class가 쓰이는지에 대해 알아보았다.

Comments