본문 바로가기
JavaScript

[자바스크립트] 프로토타입과 클래스의 차이점

by 메이플 🍁 2022. 3. 23.

자바스크립트는 2015년 6월에 여러가지 새로운 기능이 추가된 큰 업데이트를 하게됩니다. 이 업데이트를 에크마 스크립트 프로그래밍 버전 6(version 6 of the ECMA Script programming language) 줄여서 ES6라고 부릅니다.

 

ES6이전 자바스크립트에서는 클래스가 없었고 프로토타입(prototype)이라는 문법을 사용해 새로운 객체를 찍어내는 템플릿을 만들었습니다.

 

1. 객체를 찍어내는 템플릿 프로토타입, 클래스가 필요한 이유

아래의 코드와 같이 name이라는 키를 가지고 있고 farewell()이라는 함수를 가지고 있는 4개의 각기다른 person이라는 객체를 만든다고 가정해보자. 

person1 = {
  name: 'John',
  farewell: function (){
    console.log(this.name + ' has left the chat. Bye for now!');
  }
}

person2 = {
  name: 'Paul',
  farewell: function (){
    console.log(this.name + ' has left the chat. Bye for now!');
  }
}

person3 = {
  name: 'George',
  farewell: function (){
    console.log(this.name + ' has left the chat. Bye for now!');
  }
}

person4 = {
  name: 'Ringo',
  farewell: function (){
    console.log(this.name + ' has left the chat. Bye for now!');
  }
}

이런식으로 person이라는 객체를 100개 200개 만드는 일은 비효율적이다. 키 이름 name과 함수가 겹치는데 이것을 재사용할 수 있게 템플릿을 만드는 방법이 첫번째 프로토타입을 활용하는 방법 두번째 클래스를 활용하는 방법이다.

 

2. 프로토타입(prototype)

function Person(name) {
  this.name = name
}

Person.prototype.farewell = function() {
  console.log(this.name + ' has left the chat. Bye for now!');
};

var person1 = new Person('John');

console.log(person1)
/*
{
  farewell: function() {
  console.log(this.name + ' has left the chat. Bye for now!');
},
  name: "John"
}
*/

person1.farewell();
// "John has left the chat. Bye for now!"

🔍  코드 해석 

  1. Person이라는 새로운 객체를 찍어낼 수 있는 템플릿을 함수 형태로 만든다.
  2. 이때 Person안에 새로운 메소드를 추가하기위해서 prototype을 사용하였다. prototype은 Person이라는 함수에 새로운 속성이나 메소드를 추가하고 싶을때 사용하는 키워드다. prototype을 사용해 속성이나 메소드를 함수에 상속시킬 수 있다.
  3. 변수 person1에 새로운 객체를 만들기위해 미리 만들어둔 함수를 new Person을 사용해 불러온다. 이때 함수의 파라미터로 문자열 John을 전달해줬다.
  4. perosn1은 함수 Person의 템플릿을 가져와 name값에 John을 전달해주었으므로 name: 'John'이라는 프로퍼티와 함수 farewell을 가진 객체를 의미한다.
  5. 그러므로 person1.farewell()은 person1에 있는 함수 farewell를 실행시키므로 콘솔창에 위와 같은 결과가 나타난다.

 

3. 클래스(class)

class Person {
  constructor(name) {
    this.name = name
  }
  farewell() {
    console.log(this.name + ' has left the chat. Bye for now!');
  }
}

var person1 = new Person('John');

console.log(person1);
/*
{
  farewell: function() {
  console.log(this.name + ' has left the chat. Bye for now!');
},
  name: "John"
}
*/

person1.farewell();
// "John has left the chat. Bye for now!"

🔍  코드 해석

  1. Person이라는 새로운 객체를 찍어낼 수 있는 템플릿을 클래스 형태로 만든다.
  2. 클래스안에는 프로퍼티를 만드는 constructor와 메소드 farewell()함수가 있다.
  3. 변수 person1에 클래스를 사용하여 새로운 객체를 만든다.
  4. person1안에는 클래스 Person의 프로퍼티와 메소드가 담겨 있으므로 콘솔창에 위와 같은 결과가 나타난다.

댓글