Modern JavaScript #9 프로토타입과 클래스

이말감·2021년 8월 9일
0

JavaScript

목록 보기
9/13

객체 생성자

: 함수를 통해 새로운 객체를 만들고 그 안에 넣고 싶은 값 혹은 함수들을 구현할 수 있게 해준다.

function Animal(type, name, sound) {
  this.type = type;
  this.name = name;
  this.sound = sound;
  this.say = function() {
    console.log(this.sound);
  };
}

const dog = new Animal('개', '멍멍이', '멍멍');
const cat = new Animal('고양이', '야옹이', '야옹');

dog.say();
cat.say();
//멍멍
//야옹

객체 생성자를 사용할 때는 보통 함수의 이름을 대문자로 시작하고, 새로운 객체를 만들 때에는 new 키워드를 앞에 붙여주어야 한다.
위 코드를 보면 dog가 가지고 있는 say 함수와 cat이 가지고 있는 수행하는 코드가 똑같음에도 불구하고 객체가 생성될 때마다 함수도 새로 만들어져 this.say로 설정되고 있다.
같은 객체 생성자 함수를 사용하는 경우, 특정 함수 또는 값을 재사용할 수 있는데 바로 프로토타입이다.

프로토타입

: 다음과 같이 객체 생성자 함수 아래에 .prototype.[원하는 키] = 코드를 입력하여 설정할 수 있다.

function Animal(type, name, sound) {
  this.type = type;
  this.name = name;
  this.sound = sound;
}

Animal.prototype.say = function() {
  console.log(this.sound);
}
Animal.prototype.sharedValue = 1;
const dog = new Animal('개', '멍멍이', '멍멍');
const cat = new Animal('고양이', '야옹이', '야옹');

dog.say();
cat.say();

console.log(dog.sharedValue);
console.log(cat.sharedValue);

위 코드에서는 Animal.prototype.say = 를 통해 say라는 함수를 만들어냈고, 콘솔창에 출력되도록 하였다. 그리고 Animal.prototype.sharedValue = 1;도 또한 프로토타입이다.

객체 생성자 상속받기

: 예를 들어 Cat과 Dog라는 새로운 객체 생성자를 만든다고 가정하자. 그리고 해당 객체 생성자들에서 Animal의 기능을 재사용한다고 가정하자. 그럼 다음과 같이 구현할 수 있다.

function Animal(type, name, sound) {
  this.type = type;
  this.name = name;
  this.sound = sound;
}

Animal.prototype.say = function() {
  console.log(this.sound);
}
Animal.prototype.sharedValue = 1;

function Dog(name, sound) {
  Animal.call(this, '개', name, sound);
}
Dog.prototype = Animal.prototype;

function Cat(name, sound) {
  Animal.call(this,'고양이', name, sound);
}
Cat.prototype = Animal.prototype;

const dog = new Dog('멍멍이', '멍멍');
const cat = new Cat('야옹이', '야옹');

dog.say();
cat.say();

새로 만든 Dog와 Cat 함수에서 Animal.call을 호출해주고 있다. 여기서 첫 번째 인자에는 this를 넣어주어야 하고, 그 이후에는 Animal 객체 생성자 함수에서 필요로 하는 파라미터를 넣어주어야 한다.
추가적으로 prototype을 공유해야 하기 때문에 상속받은 객체 생성자 함수를 만들고 나서 prototype 값을 Animal.prototype으로 설정했다.

-> 이때 Cat, Dog라는 객체 생성자가 그냥 Animal이라는 객체 생성자를 사용할 때는

function Animal(type, name, sound) {
  this.type = type;
  this.name = name;
  this.sound = sound;
}

Animal.prototype.say = function() {
  console.log(this.sound);
}
Animal.prototype.sharedValue = 1;

function Dog(name, sound) {
  Animal.call(this, '개', name, sound);
}

function Cat(name, sound) {
  Animal.call(this,'고양이', name, sound);
}

위와 같이 적어줘도 되는데 프로토 타입을 사용할 때는 꼭
Dog.prototype = Animal.prototype;
를 적어줘야 한다.
그러니까 객체 생성자에서 객체 생성자꺼를 빌려오면서 프로토타입을 사용할 때는 작성해야하고, 일반적으로 const dog = new Animal(....) 같이 그냥 사용할 때는 작성하지 않아도 된다.

클래스

: 클래스라는 기능은 다른 프로그래밍 언어에는 있는 기능인데 자바스크립트에는 없었기 때문에 예전 자바스크립트(ES5)에서는 클래스 문법이 따로 없었기 때문에 위에서 작성한 코드처럼 객체 생성자 함수를 사용하여 비슷한 작업을 구현해왔다.
ES6에서부터는 class라는 문법이 추가되었다. 우리가 객체 생성자로 구현했던 코드를 조금 더 명확하고, 깔끔하게 구현할 수 있게 해준다. 추가적으로 상속도 훨씬 쉽게 해줄 수 있다.

class Animal{
  constructor(type, name, sound) {
    this.type = type;
    this.name = name;
    this.sound = sound;
  }
  say() {
    console.log(this.sound);
  }
}

const dog = new Animal('개', '멍멍이', '멍멍');
const cat = new Animal('고양이', '야옹이', '야옹');

dog.say();
cat.say();

여기서 say라는 함수를 클래스 내부에 선언했다. 클래스 내부의 함수를 '메서드'라고 부른다. 이렇게 메서드를 만들면 자동으로 prototype으로 등록이 된다.

class Animal{
  constructor(type, name, sound) {
    this.type = type;
    this.name = name;
    this.sound = sound;
  }
  say() {
    console.log(this.sound);
  }
}

class Dog extends Animal {
  constructor(name, sound) {
    super('개', name, sound);
  }
}

class Cat extends Animal {
  constructor(name, sound) {
    super('고양이', name, sound);
  }
}

const dog = new Dog('멍멍이', '멍멍');
const cat = new Cat('야옹이', '야옹');

dog.say();
cat.say();

상속을 할 때는 extends 키워드를 사용하며, constructor에서 사용하는 super() 함수가 상속받은 클래스의 생성자를 가르킨다.

profile
전 척척학사지만 말하는 감자에요

0개의 댓글