Jieunny์˜ ๋ธ”๋กœ๊ทธ

S2) Unit2. [์‹ค์Šต] Beesbeesbees ๋ณธ๋ฌธ

CodeStates/Training

S2) Unit2. [์‹ค์Šต] Beesbeesbees

Jieunny 2023. 1. 16. 17:00

๐Ÿ“ฃ  ์ƒ์†์„ ์ด์šฉํ•ด์„œ ํด๋ž˜์Šค ๊ตฌํ˜„ํ•˜๊ธฐ

โœ”๏ธ ๊ณ„์ธต ๊ตฌ์กฐ

 

๐Ÿ“ฃ  super, extends ๋ž€?

โœ”๏ธ super() : ๋ถ€๋ชจ ํด๋ž˜์Šค์˜ ํ•จ์ˆ˜๋ฅผ ํ˜ธ์ถœํ•  ๋•Œ ์‚ฌ์šฉํ•œ๋‹ค.

this ํ‚ค์›Œ๋“œ๊ฐ€ ์‚ฌ์šฉ๋˜๊ธฐ ์ „์— ํ˜ธ์ถœ๋˜์–ด์•ผ ํ•œ๋‹ค. -> ์•ˆ๊ทธ๋Ÿฌ๋ฉด ์ฐธ์กฐ์˜ค๋ฅ˜ ๋ฐœ์ƒ

 

โœ”๏ธ extends() : ํด๋ž˜์Šค๋ฅผ ๋‹ค๋ฅธ ํด๋ž˜์Šค์˜ ์ž์‹์œผ๋กœ ๋งŒ๋“ค ๋•Œ ์‚ฌ์šฉํ•œ๋‹ค.

class ๊ธฐ๋ฐ˜์œผ๋กœ ์ƒ์†์„ ๋ฐ›๋Š” ๊ฒƒ์ฒ˜๋Ÿผ ๋ณด์ด์ง€๋งŒ, JS๋Š” prototype ๊ธฐ๋ฐ˜์˜ ์–ธ์–ด์ด๊ธฐ ๋•Œ๋ฌธ์— ๋‚ด๋ถ€์ ์œผ๋กœ๋Š” prototype chain์„ ํ†ตํ•ด ์ƒ์†์ด ์ด๋ฃจ์–ด์ง„๋‹ค.

 

 

๐Ÿ“ฃ  ์ฝ”๋“œ

1๏ธโƒฃ Grub.js

class Grub {	
  constructor(){
    this.age = 0;
    this.color = 'pink';
    this.food = 'jelly';
  }

  eat() {
    return `Mmmmmmmmm ${this.food}`;
  }
}

โžฐ ๋ถ€๋ชจ ํด๋ž˜์Šค ์ด๋ฏ€๋กœ ์ƒ์„ฑ์ž๋งŒ ์ƒ์„ฑํ•ด์ฃผ๋ฉด ๋œ๋‹ค.

 

2๏ธโƒฃ Bee.js

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

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

module.exports = Bee;

โžฐ age์™€ color๋Š” Grub ํด๋ž˜์Šค์—์„œ ์ƒ์†๋ฐ›์•˜๋‹ค.

โžฐ  Grub.js์—์„œ Grubํด๋ž˜์Šค๋ฅผ ๊ฐ€์ ธ์™€์•ผ ์ƒ์† ๊ฐ€๋Šฅํ•˜๋‹ค.

 

3๏ธโƒฃ HoneyMakerBee.js

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

class HoneyMakerBee extends Bee{
  constructor(){
    super();
    this.age = 10;
    this.job = 'make honey';
    this.honeyPot = 0;
  }

  makeHoney() {
    this.honeyPot++;
  }

  giveHoney() {
    this.honeyPot--;
  }
}

module.exports = HoneyMakerBee;

โžฐ Grub๋ฅผ ์ƒ์†๋ฐ›์€ Bee๋ฅผ ์ƒ์†ํ•˜๊ณ  ์žˆ๊ธฐ ๋•Œ๋ฌธ์— age๋ฅผ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.

 

4๏ธโƒฃ ForagerBee.js

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

class ForagerBee extends Bee {
  constructor(){
    super();
    this.age = 10;
    this.job = 'find pollen';
    this.canFly = true;
    this.treasureChest = [];
  }

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

module.exports = ForagerBee;

โžฐ HoneyMakerBee.js์™€ ๋งˆ์ฐฌ๊ฐ€์ง€.