이론으로 봤을 때는 어렵지 않았었는데 막상 문제를 보고 풀려고 하니 당황스러웠다.
익숙해질 수 있게 연습해보자🚗🚗🚗
[프로토타입 체인]
JavaScript 객체 지향 프로그램에서 상속을 구현할 때 사용한다.
문제1) 클래스 SweetLemon의 `flavor` 속성은 `lemon`이어야 한다.
class SweetLemon{
constructor(flavor = `lemon`){
this.flavor = `lemon` // this.flavor = flavor
}
}
문제2) 클래스SweetLemon의 `eat` 메소드가 존재해야 하고, `eat` 메소드를 통해 레몬을 먹는다.
class SweetLemon{
constructor(flavor = `lemon`){
this.flavor = `lemon`
}
eat(){
return `${(this.flavor)} flavor` // lemon flavor
//탬플릿 리터럴: 내장된 표현식을 허용하는 문자열.
}
문제3) 클래스 Lemonade의 `iced` 속성은 true 여야 한다.
class Lemonade{
constructor(iced = true){
this.iced = true
}
}
문제4) 클래스 Lemonade의 `quantity` 속성은 1 이어야 한다.
class Lemonade{
constructor(iced = true, quantity = 1){
this.iced = true
this.quantity = 1
}
}
문제5) 클래스 Lemonade의 `topping` 속성은 빈 배열 `[]` 이어야 한다.
class Lemonade{
constructor(iced = true, quantity = 1, this.topping = []){
this.iced = true
this.quantity = 1
this.topping = []
}
}
문제6) `flavor` 속성은 `SweetLemon`으로부터 상속 받는다.
class Lemonade extends SweetLemon{
constructor(iced = true, quantity = 1, this.topping = []){
this.iced = true
this.quantity = 1
this.topping = []
//this.flavor = `lemon`
}
}
문제7) `eat` 메서드는 `SweetLemon`으로부터 상속 받는다.
class Lemonade extends SweetLemon{
constructor(iced = true, quantity = 1, this.topping = []){
super() //메서드를 가져올 때 속성값보다 먼저 사용
this.iced = true
this.quantity = 1
this.topping = []
//this.flavor = `lemon`
}
}
문제8) `plusQuantity` 메서드는 `quantity`에 1씩 추가한다.
class Lemonade extends SweetLemon{
constructor(iced = true, quantity = 1, this.topping = []){
super() //메서드를 가져올 때 속성값보다 먼저 사용
this.iced = true
this.quantity = 1
this.topping = []
//this.flavor = `lemon`
}
plusQuantity(quantity++){
this.quantity++
}
문제9) `minusQuantity` 메서드는 `quantity`에 1씩 삭제한다.
class Lemonade extends SweetLemon{
constructor(iced = true, quantity = 1, this.topping = []){
super() //메서드를 가져올 때 속성값보다 먼저 사용
this.iced = true
this.quantity = 1
this.topping = []
//this.flavor = `lemon`
}
plusQuantity(quantity++){
this.quantity++
}
minusQuantity(quantity--){
this.quantity--
}
}
문제10) `addTopping` 메서드를 통해 `topping` 속성에 재료를 추가한다.
class Lemonade extends SweetLemon{
constructor(iced = true, quantity = 1, this.topping = []){
super() //메서드를 가져올 때 속성값보다 먼저 사용
this.iced = true
this.quantity = 1
this.topping = []
//this.flavor = `lemon`
}
plusQuantity(quantity++){
this.quantity++
}
minusQuantity(quantity--){
this.quantity--
}
addTopping(ingredients){
this.addTopping.push(ingredients)
}
}
🌈 constructor 에 들어가는 변수를 꼭 적어줘야 하는 이유: 가독성 때문
🌈 super() 에 변수가 들어가지 않는 것을 추천. 복잡하기 때문.
⭐️⭐️⭐️중요⭐️⭐️⭐️
- 속성을 상속받는 방법은 class (현재 클래스) extends (상속 받을 클래스) 이다.
- 메서드를 상속받는 방법은 super() 이며 속성값보다 먼저 사용한다.
'JavaScript' 카테고리의 다른 글
JQuery와 Javascript (0) | 2023.05.23 |
---|---|
동기(sync)와 비동기(async) (0) | 2022.12.26 |
npm version update 하는 법 (0) | 2022.07.25 |
JavaScript 프로토타입 체인 (0) | 2022.07.25 |
JavaScript 프로토타입 (0) | 2022.07.23 |