Beesbeesbees & prototype chain

onecyn·2022년 5월 26일

프로토타입

프로토타입을 번역하자면 원형이라는 뜻으로 볼 수 있다.
자바스크립트를 Prototype based language라고도 할 정도로 중요하다.
객체 생성 함수 안에서 정의하지 않고 밖에서 정의함.

프로토타입이 필요한 이유

function Person(name,first,second,third){
    this.name = name;
    this.first = first;
    this.second = second;
    this.third = third;
    this.sum = function(){ 
        return this.first+this.second+this.third;
    }
}


var kim = new Person('kim',10,20,30);
var lee = new Person('lee',10,10,10);

위와 같은 생성자 함수에서는 새로운 객체가 생성될 때 마다 sum이라는 내부 메소드가 새롭게 생성되고 있다.
그만큼 메모리 낭비가 발생해 성능이 떨어진다.

또 sum 이라는 메소드의 내용을 수정하고 싶은 경우
만들어진 객체만큼 수정 작업을 반복해야한다는 문제가 있다.
생산성이 떨어지게 된다.

프로토타입을 사용하면

  • prototype 은 메소드를 공유시켜주는 키워드 , 생성자를 통해 만든 객체가 공통적으로 사용하는 함수를 만들 수 있어서 성능 및 생산성 개선에 도움이 된다. (객체의 재사용성)

Person 생성자에 prototype에 sum이라는 함수를 정의하면

function Person(name,first,second,third){
    this.name = name;
    this.first = first;
    this.second = second;
    this.third = third;
    
}
Person.prototype.sum = function(){ 
    return this.first+this.second+this.third;
}

var kim = new Person('kim',10,20,30);
var lee = new Person('lee',10,10,10);
console.log("kim.sum()",kim.sum());
console.log("lee.sum()",lee.sum());

생성자 함수 안에 메소드를 정의하는 코드가 들어 있지 않기 때문에
객체가 생성될 때마다 호출되지 않고 한번만 생성하게 된다.
즉 메모리를 절약할 수 있다.

또, 하나의 객체에만 메소드를 추가할 수 있다.
자바스크립트는 객체에서 어떠한 메소드 또는 속성을 출력할때
해당 객체가 그 메소드 또는 속성을 가지고 있는지를 확인하기 때문이다.

만약 가지고 있다면 객체 내의 메소드 또는 속성을 호출하고
없다면 이 객체의 생성자의 prototype에 해당 메소드 또는 속성이 정의 되어 있는지를 확인한다.

생성자를 이용한 객체 생성

객체의 속성들 (변수들)은 생성자 함수 안에 넣는 것이 일반적이다.
객체의 메소드들은 생성자의 prototype에 추가하는 것이 일반적이다.

function Person(name,first,second,third){
    this.name = name;
    this.first = first;
    this.second = second;
    this.third = third;
    
}
Person.prototype.sum = function(){ 
    return 'prototype : ' + (this.first+this.second+this.third);
}

Beesbeesbees

다양한 종류의 꿀벌 Class가 존재하는 repository의 Class Structure를 구현하며 class keyword를 이용한 상속을 학습하는 과제.


Class Structure
├── Grub
│   └── Bee
│       ├── HoneyMakerBee
│       └── ForagerBee

위의 class structure에서 볼 수 있는 것처럼, 모든 Bee는 Grub을 기반으로 하여 각자의 특성에 맞는 일을 받게 된다. 공통된 특성을 기반으로 각자에게 맞는 특성을 부여받을 수 있는 것은 상속이 이루어졌음을 의미한다.

<Bee.js>

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

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

module.exports = Bee;

class에 extends를 함으로써 Grub 속성을 상속 받는다.
super() 키워드를 통해서, 상위 클래스의 생성자를 호출.

<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;

forage 메소드에 파라미터를 넣으면, 다형성으로 작동할 수 있다.

<Grub.js>

class Grub {
  constructor(){
    this.age=0
    this.color='pink'
    this.food='jelly'
  }
  eat(){
    return `Mmmmmmmmm ${this.food}`
  }
}

module.exports = Grub;

<HoneyMakerBee.js>

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

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

  }
  makeHoney(){
    this.honeyPot++
  }
  giveHoney(){
    this.honeyPot--
  }
}

module.exports = HoneyMakerBee;




profile
chaeyun.me@gmail.com

0개의 댓글