클래스는 객체를 생성하기 위한 템플릿이다.
같은 템플릿으로 여러 객체를 생성할 수 있다.
책이라는 템플릿을 클래스로 작성한다면 다음과 같다.
ES5 클래스 작성 문법
function Book(author, title, price) { this.author = author; this.title = title; this.price = price; }
ES6 클래스 작성 문법
class Book { constructor(author, title, price) { this.author = author; this.title = title; this.price = price; } }
Book
클래스 내부에 작성된 author
, title
, price
는 각각 Book
클래스의 속성이다.
ES5 문법에서는 function
으로 클래스가 선언되었다.
하지만 ES6 문법에는 class
키워드가 추가되었다. 그리고 constructor
함수로 각 속성에 값을 할당한다.
- 생성자 함수
constructor
인스턴스가 초기화될 때 실행하는 생성자 함수이다.
인스턴스는 클래스라는 템플릿으로 생성된 객체이다.
new
키워드
새로운 인스턴스를 생성한다. 이때new
로 생성된 인스턴스가this
에 해당한다.const careerSkill = new Book('John', 'Career Skill', 28000); /* { this.author = 'John'; this.title = 'Career Skill'; this.price = 28000; } */ const cleanCode = new Book('Robert', 'Clean Code', 33000); /* { this.author = 'Robert'; this.title = 'Clean code'; this.price = 33000; } */
careerSkill
과 cleanCode
는 각각 Book
클래스의 인스턴스이다.