Javascript

Beesbeesbees 과제풀이

becky(지은) 2023. 3. 16. 14:48
문제

src 디렉토리 안에는 클래스가 존재합니다.

  • constructor, super, extends, class 키워드를 이용하여 구현합니다.
  • 상속과 관련된 키워드 super, extends는 공식문서를 읽어본 후 적용해봅니다.

 

 

풀이

먼저 Grub 을 완성한뒤, Bee, HoneMakerBee,ForagerBee 순서대로 완성하면 됩니다.

class Grub {
  // TODO..
  constructor(){  // class는 항상 constructor()를 포함한다
  this.age = 0;
  this.color = `pink`;
  this.food = `jelly`;
}
 eat(){
  return `Mmmmmmmmm jelly` // 콘솔이 아니라 리턴을 써야 했다
 }
}

module.exports = Grub;
const Grub = require('./Grub');

class Bee extends Grub {
  // TODO..
   constructor(){
    super(); // 상위클래스(부모클래스) 호출, 항상 this 키워드보다 먼저
    this.age = 5;
    this.color = `yellow`;
    this.job = `Keep on growing`;

}
}
// 자기 자신에게 그 속성이 없으면 부모, 또는 그 부모의 속성을 조회하는 패턴
//`food` 속성은 Grub으로부터 상속받습니다
// `eat` 메소드는 Grub으로부터 상속받습니다

module.exports = Bee;
const Bee = require('./Bee');

class ForagerBee extends Bee {
  constructor(){
    super(); //super() 키워드는 반드시 this키워드 이전에 호출되어야 함
    this.age = 10; // 나이는 숫자로 할당
    this.job = `find pollen`;
    this.canFly = true; // true는 그 자체로 할당
    this.treasureChest = []; //문자열이 아닌 빈배열을 할당
  }
  forage(보물){
    return this.treasureChest.push(보물); // 변수가 들어갈 구멍을 만들어줌
                                         //push()는 배열의 끝에 하나이상의 요소를 추가할때 씀!
  }
  // TODO..
}

module.exports = ForagerBee;
const Bee = require('./Bee');

class HoneyMakerBee extends Bee{
  constructor(){
    super();
    this.age = 10;
    this.job = 'make honey'
    this.honeyPot = 0;
  }
  makeHoney(){
  // 호출할때 기존값이 1씩 커짐
   return this.honeyPot = this.honeyPot + 1 ; // 또는 this.honeyPot+=1 (증가값은 1이다/띄어쓰기X)
  }
  giveHoney(){
  // 호출할때 기존값이 1씩 작아짐
   return this.honeyPot = this.honeyPot - 1 ; // 또는 this.honeyPot-=1 (감소값은 1이다/띄어쓰기X)
  }
}

module.exports = HoneyMakerBee;