
코드스테이츠 과제 코드를 공부 목적으로 변형 해서 정리 하였습니다.
🍀문제 코드
extends, super, this를 사용하여 다음 Todo를 해결 하세요.
class Human {
/* TODO..
* Human 클래스 age 속성은 '35',food 는 'cookie', job 은 'teacher' 이어야 한다
* */
}
class Student {
/* TODO..
* Student 클래스는 Human 클래스에서 food 속성을 상속받는다.
* age 속성은 '19', job 속성은 'student' 이어야한다.
* lunch 메서드가 존재하고 '점심을 먹습니다' 가 출력 됩니다.
* */
}
class JuniorFreshman {
/* TODO..
* JuniorFreshman 클래스는 Student 클래스에서 job 속성을 상속 받습니다.
* JuniorFreshman 클래스는 Human 클래스에서 food 속성을 상속받는다.
* age 속성은 '17'이어야 한다. point 속성은 0입니다. gift 속성은 빈 배열입니다.
* plusPoint 메소드는 point 에 1씩 추가합니다
* minusPoint 메소드는 point 에 1씩 뺍니다
* getGift 메소드를 통해 gift 속성에 선물을 추가 할 수 있어야 합니다.
* lunch 메서드가 잘 실행 됩니다.
* */
}
🍀해결 코드
class Human {
constructor() {
this.age = 35;
this.food = 'cookie';
this.job = 'teacher';
}
}
class Student extends Human{
constructor(food) {
super(food);
this.age = 19;
this.job = 'student';
}
lunch(){return '점심을 먹습니다.';}
}
class JuniorFreshman extends Student{
constructor(job,food) {
super(job,food);
this.age = 17;
this.job = 'student';
this.gift = [];
this.point = 0;
}
plusPoint(){return this.point++;}
minusPoint(){return this.point--;}
getGift(item){return this.gift.push(item);}
}
🍀테스트 코드
const human = new Human
const student = new Student
const junior = new JuniorFreshman
console.log(human.age); //35
console.log(human.food); //cookie
console.log(human.job); //teacher
console.log(student.age); //19
console.log(student.food); //cookie
console.log(student.job); //student
console.log(student.lunch()); //점심을 먹습니다.
console.log(junior.age); //17
console.log(junior.food); //cookie
console.log(junior.job); //student
console.log(junior.point); //0
console.log(junior.gift); //[]
console.log(junior.lunch()); //점심을 먹습니다
junior.plusPoint();
junior.plusPoint();
junior.plusPoint();
junior.minusPoint();
console.log(junior.point); //2
junior.getGift('card');
junior.getGift('onion');
junior.getGift('cash');
console.log(junior.gift); //['card', 'onion', 'cash']
🤓 새로 알게 된 내용
this
class JuniorFreshman extends Student{
constructor() {
this.gift = [];
this.point = 0;
}
plusPoint(){return this.point++;}
minusPoint(){return this.point--;}
getGift(item){return this.gift.push(item);}
}
다음과 같이 constructor 안에 속성 this.gift, this.point처럼 this를 사용할 경우 this는 자기 자신 객체 안에서 사용이 가능하다.
class도 객체 이기 때문에 this.gift는 JuniotFreshman 클래스 안에서 사용이 가능하다.
메소드 plusPoint와 minusPoint도 point를 정의 하지 않았지만 this를 사용하여 값에 영향을 줄수 있다.
⚠ 작성자가 이해한 방식으로 작성하였다. 오류가 있을수 있다.
함수가 객체의 프로퍼티 값이면 메소드로서 호출된다.
이때 메소드 내부의 this는 해당 메소드를 소유한 객체, 즉 해당 메소드를 호출한 객체에 바인딩된다.
poiemaweb 글 참고
🦦 잡담
객체지향과 프로토 타입을 공부하면서 진행한 문제였습니당
아직 class와 상속이 어색하고,,,
this new prototype __proto__ 헷갈립니다.
this는 이해한 내용이 맞는지 모르겠는데 페어분과 의논했을때 가장 맞다고 생각했던 내용을 정리해봤슴둥
그럼 끗 🤓
🐾참고
'프론트엔드 > 코딩노트' 카테고리의 다른 글
| [코드스테이츠 과제] fetch API (0) | 2022.09.27 |
|---|---|
| [코드스테이츠 과제] Node.js모듈 - fs모듈 (0) | 2022.09.27 |
| [코드스테이츠 과제] 비동기 - 타이머 API (0) | 2022.09.27 |
| [코플릿] DailyCoding - 짝수 인덱스는 키, 홀수 인덱스는 값인 객체 (1) | 2022.09.23 |
| [코플릿] 객체 - 다른 객체들의 속성 가져오기 (1) | 2022.09.23 |