: 하나의 모델이 되는 청사진(class
)를 만들고, 청사진을 바탕으로 한 객체(instance
)를 만드는 프로그래밍 패턴
데이터와 기능을 한 번에 묶어서 처리한다.
객체 생성 기준이 되는 청사진
함수로 선언한다 (일반적으로 함수명은 대문자로 시작하며 일반명사를 사용한다.)
return
이 없다
함수 내부에 객체 속성을 정의한다.
객체 속성이란? key와 value의 묶음
클래스 생성자 함수
- ES5 문법
function Summer(month, weather, fruit) { //인스턴스가 만들어질 때 실행하는 코드 //class 속성 정의 this.month = month; //key 'month'에 매개변수 month를 담는다. this.weather = weather; this.fruit = fruit; }
- ES6 문법
class Summer { constructor(month, weather, fruit) { //인스턴스가 만들어질 때 실행하는 코드 this.month = month //마찬가지로 객체 속성을 정의한다. this.weather = weather; this.fruit = fruit; } }
this : 인스턴스 객체를 의미하는 키워드 constructor(){...} : 인스턴스가 초기화 될 때 실행하는 생성자 메서드
class를 바탕으로 생성한 객체 (instance object)
: 클래스의 고유한 속성과 메서드를 갖는다.
: new
객체 생성 키워드로 선언한다.
인스턴스 생성자 함수
(클래스 생성자 함수와 이어진다)
let may = new Summer(5, 'sunny', 'strawberry');
console.log(may); Summer {month: 5, weather: 'sunny', fruit: 'strawberry'}
method란? 객체에 딸린 함수
Summer에 flower()메서드를 정의하려면?
- ES5 문법
function
키워드로 선언한다.
class명.prototype.method명 = function(...) {...}
//1. class 메서드 정의 Summer.prototype.flower = function(str) { console.log(`${this.month}월에는 ${str}꽃이 핍니다.` ) }; //2. 인스턴스에서 메서드 호출하기 may.flower('장미'); >5월에는 장미꽃이 핍니다.
- ES6 문법
: 클래스 생성자 내부에 작성한다.//1. class 메서드 정의 class Summer { constructor(/* 생략 */) { /* 인스턴스가 만들어질 때 실행하는 코드 객체 속성 정의 */ } flower(str) { console.log(`${this.month}월에는 ${str}꽃이 핍니다.` ) }; //2. 인스턴스 생성 + 메서드 호출하기 let june = new Summer (6, 'rainy', 'watermelone'); june.flower('해바라기'); >6월에는 해바라기꽃이 핍니다.
prototype
: class를 만들 때 쓰는 원형 객체(original form)
this
: 함수가 실행될 때 해당 scope마다 생성되는 고유한 execution context에서 this value가 결정된다.
: new 키워드로 인스턴스를 생성하면 해당 인스턴스가 this value가 된다.