코로 넘어져도 헤딩만 하면 그만
Bees (프로토타입 체인 과제 해설) 본문
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가 쓰이는지에 대해 알아보았다.
'CODE STATES 44' 카테고리의 다른 글
주말공부: 구조분해할당 (0) | 2023.03.19 |
---|---|
주말공부:스코프, 클로저 복습 with Unit9 종합퀴즈 (0) | 2023.03.19 |
객체 지향 프로그래밍 1-4) 프로토타입 체인 (0) | 2023.03.16 |
자주 쓰이는 터미널 명령어, Git 명령어 (0) | 2023.03.15 |
객체 지향 프로그래밍 1-3) 프로토타입과 클래스 (0) | 2023.03.15 |