본문 바로가기

ES5 생성자 함수와 ES6 class

by 김홍중 2022. 1. 14.

객체 지향 프로그래밍의 종류

- 객체 지향 프로그래밍은 class 기반과 prototype 기반으로 나눌 수 있다.

- class 기반은 java나 c++을 예로 들 수 있고 prototype 기반은 javascript를 예로 들 수 있다.

javascript의 객체 지향 프로그래밍

- javascript는 class가 필요없는 prototype 기반 객체지향 프로그래밍이다.

- 물론 ES6부터 class가 추가 되었지만 java나 c++의 class와 다르다.

- ES6 class도 프로토타입 기반이다.


- ES5 생성자 함수와 ES6 class는 모두 프로토타입 기반의 인스턴스를 생성할 수 있다.

 

class 뿐만 아니라 ES5 생성자 함수로도 구현하려는 이유는?

 

- class는 기존의 생성자 함수에서 기능적으로 크게 개선되었다기 보다는 class 기반의 객체 지향의 프로그래밍을 하였던 개발자들이 더 편하게 배울 수 있도록 생성자 함수에서 구현하는 코드를 가린다고 생각하였다. 그래서 classa로만 공부하면 오히려 프로토타입에 대한 이해가 부족할 수 있다고 생각하였다. 물론 생성자 함수와 달리진 점도 있지만 그것이 크지 않다고 판단하였다. 그런데 class로 짠 코드를 생성자 함수로 구현이 가능한지 먼저 판단을 하고 구현의 설계를 해야 생성자 함수에 대한 이해가 부족해서 에러가 나는것인지 판단할 수 있다고 생각하였다. 그런데 아래 실습에서 class로 짠 코드에서 super하는 부분을 생성자 함수로 짜는 것을 실패하여서 이를 해결해야한다.

 

생성자 함수와 class 실습

 - class

class Animal {
  constructor(name) {
    this.foodNum = 0;
    this.name = name;
  }

  eat(foodNum) {
    this.foodNum = foodNum;
    console.log(`${this.name}가 먹이 ${this.foodNum}개를 먹었습니다.`);
  }

  run() {
    console.log(`${this.name}가 달렸습니다.`);
  }
}

class Dog extends Animal {
  sleep() {
    console.log(`${this.name}가 잠들었습니다.`);
  }

  eat(foodNum) {
    super.eat(foodNum);
    this.sleep();
  }
}

const dog = new Dog('초록 강아지');
const puppy = new Dog('보라 강아지');

dog.run();
dog.eat(5);

puppy.run();
puppy.eat(8);

console.log(dog);



- 생성자 함수

function Animal(name) {
  this.foodNum = 0;
  this.name = name;
  console.log(this);
}

Animal.prototype.eat = function (foodNum) {
  this.foodNum = foodNum;
  console.log(`${this.name}가 먹이 ${this.foodNum}개를 먹었습니다.`);
};

Animal.prototype.run = function () {
  console.log(`${this.name}가 달렸습니다.`);
};

function Dog(name) {
  Animal.call(this, name);
  console.log(this);
}

Dog.prototype = Object.create(Animal.prototype);

Dog.prototype.constructor = Dog;

Dog.prototype.sleep = function () {
  console.log(`${this.name}가 잠들었습니다.`);
};

Dog.prototype.eat = function (foodNum) {
   //Animal.prototype.eat(foodNum);
   //Dog.prototype.sleep();
};

const dog = new Dog('초록 강아지');
const puppy = new Dog('보라 강아지');

dog.run();
//dog.eat(5);

puppy.run();
//puppy.eat(8);

console.log(dog);

 

class의 객체 결과

 

생성자 함수의 객체 결과

결과 두 개를 비교하여 [[Prototype]]에서 상속이 잘 이루어 지는것을 볼 수 있었다. [[Prototype]]을 펼쳐서 여러 함수들이 속해 있는 것을 확인하였다.

댓글