객체 지향 프로그래밍 : 하나의 모델이 되는 청사진(Blueprint)을 만들고, 그 청사진을 바탕으로 한 객체를 만드는 프로그래밍 패턴
function Car(color) { }; // 클래스(class)
let avante = new Car('blue'); // 인스턴스(instance)
let mini = new Car('cyan'); // 인스턴스(instance)
let beetles = new Car('red'); // 인스턴스(instance)
// ES5 : 클래스 정의
function Car(brand, name, color) {
// 인스턴스가 만들어질 때 실행되는 코드
}
// ES6 : 'class' 라는 키워드를 이용해서 정의
class Car {
constructor(brand, name, color) {
// 인스턴스가 만들어질 때 실행되는 코드
}
}
인스턴스를 만들 때에는 new
키워드를 사용한다.
즉시 생성자 함수가 실행되며, 변수에 클래스의 설계를 가진 새로운 객체(인스턴스)가 할당된다.
각각의 인스턴스는 클래스의 고유한 속성과 메서드를 갖게 된다.
let avante = new Car('hyundai','avante', 'black');
let mini = new Car('bmw', 'mini', 'white');
let beetles = new Car('volkswagen', 'beetles', 'red');
this
키워드는 인스턴스 객체를 의미한다.
parameter로 넘어온 브랜드, 이름, 색상 등은 인스턴스 생성 시 지정하는 값이며,
위와 같이 this에 할당한다는 것은 만들어진 인스턴스에 해당 브랜드, 이름, 색상을 부여하겠다는 의미이다.
// ES5 : 클래스 정의
function Car(brand, name, color) {
this.brand = brand;
this.name = name;
this.color = color;
}
// ES6 : 'class' 라는 키워드를 이용해서 정의
class Car {
constructor(brand, name, color) {
this.brand = brand;
this.name = name;
this.color = color;
}
}
// ES5 : 'prototype' 이라는 키워드를 사용해야 메서드를 정의할 수 있다.
function Car(brand, name, color) { /* 생략 */ }
Car.prototype.refuel = function() {
// 연료 공급을 구현하는 코드
}
Car.prototype.drive = function() {
// 운전을 구현하는 코드
}
// ES6 : 생성자 함수와 함께 class 키워드 안쪽에 묶어서 정의한다.
class Car {
contructor(brand, name, color) { /* 생략 */ }
refuel(){
}
drive(){
}
}
let avante = new Car('hyundai', 'avante', 'black');
avante.color; // 'black'
avante.drive(); // '아반떼가 운전을 시작합니다.'
let mini = new Car('bmw', 'mini', 'white');
mini.brand; // 'bmw'
mini.refuel(); // '미니에 연료를 공급합니다.'
prototype
: 모델의 청사진을 만들 때 쓰는 원형 객체(original form)constructor
: 인스턴스가 초기화될 때 실행하는 생성자 함수this
: 함수가 실행될 때, 해당 scope 마다 생성되는 고유한 실행 context(execution context), new 키워드로 인스턴스를 생성했을 때에는 해당 인스턴스가 바로 this의 값이 됨// ES5
function Car(brand, name, color) {
this.brand = brand;
this.name = name;
this.color = color;
}
Car.prototype.drive = function() {
console.log(this.name + '가 운전을 시작합니다.');
}
let avante = new Car('hyundai', 'avante', 'black');
avante.color; // 'black'
avante.drive(); // 'avante가 운전을 시작합니다.'
// ES6 방식이 더욱 많이 쓰인다.
class Car {
constructor(brand, name, color) {
this.brand = brand;
this.name = name;
this.color = color;
drive() {
console.log(this.name + '가 운전을 시작합니다.');
}
}
}
let avante = new Car('hyundai', 'avante', 'black');
avante.color; // 'black'
avante.drive(); // 'avante가 운전을 시작합니다.'
mdn 문서에서 배열 메서드(filter, map, reduce 등등..) 검색해보면
Array.prototype.메서드명
과 같이 안내되어 있다.
이는 모든 메서드들이 클래스의 원형 객체(prototype)에 정의되어 있기 때문이다.
class Counter {
constructor() {
this.value = 0; // 생성자 호출을 할 경우, this는 new 키워드로 생성한 Counter 인스턴스
}
increase() {
this.value++;
}
decrease() {
this.value--;
}
getValue() {
return this.value;
}
}
let counter1 = new Counter() // 생성자 호출
counter1.increase();
counter1.getValue(); // 1