객체 지향 프로그래밍
은 하나의 모델이 되는 설계도를 만들고 그 설계도를 바탕으로 한 객체를 만드는 프로그래밍 패턴이다. 이 때, 설계도 바탕으로 한 객체를인스턴스 객체(instance object)
, 설계도를class
라고 할 수 있다.
class
)대문자
로 시작하는 일반명사
로 만든다.// ES5 // 클래스를 함수로 정의
function Car(brand, name, color){
// 인스턴스가 만들어질 때 부여되는 속성
}
// ES6 // 클래스를 class라는 키워드와 생성자 함수를 이용해서 정의
class Car(
constructor (brand, name, color){
// 인스턴스가 만들어질 때 부여되는 속성
}
}
ES6
에서는 생성자(constructor)
함수와 함께 class
키워드를 이용해서 정의할 수 있다.🧐 ES6 방법을 주로 사용하므로 ES6 방법을 기억하자!
instance object
)new
키워드를 써서 만든다.let genesis = new Car('hyundai', 'genesis', 'black');
let mini = new Car('bmw', 'mini', 'white');
let stinger = new Car('kia', 'stinger', 'blue');
변수에 클래스의 설계를 가진 새로운 객체, 즉 인스턴스
가 할당된다.
각각의 인스턴스는 클래스의 고유한 속성과 메서드
를 갖는다.
클래스에 속성과 메서드를 정의하고, 인스턴스에서 이용한다.
✍️ 객체에서 속성이란 키-값 쌍을 의미한다.
// ES5 //
function Car(brand, name, color){
this.brand = brand;
this.name = name;
this.color = color;
}
// ES6 //
class Car{
constructor(brand, name, color){
this.brand = brand;
this.name = name;
this.color = color;
}
}
👉 여기서 this
는 인스턴스 객체
를 의미한다. 만들어지는 인스턴스 객체의 키(key)
는 brand, name, color 이고, 값(value)
는 생성자(constructor)의 파라미터로 받은 인자(brand, name, color)이다.
ES6
에서는 생성자 함수와 함께 class 키워드 안쪽에 묶어서
정의한다. 아래 예시의 경우 refuel(){}
, drive(){}
가 메서드에 해당한다.// ES6 //
class Car {
constructor(brand, name, color){ /* 생략 */ }
refuel(){
return this.name + '에 연료를 공급합니다'
}
drive(){
return this.name + '가 운전을 시작합니다'
}
}
ES5
에서는 prototype
이라는 키워드를 사용해야 메서드를 정의할 수 있다.// ES5 //
function Car(brand, name, color){
Car.prototype.refuel = function(){
// 연료 공급을 구현하는 코드
}
Car.prototype.drive = function(){
// 운전을 구현하는 코드
}
}
let genesis = new Car('hyundai', 'genesis', 'black');
genesis.color; // 'black'
genesis.drive(); // 아반떼가 운전을 시작합니다
let mini = new Car('bmw', 'mini', 'white');
mini.brand; // 'bmw'
mini.refuel(); // 미니에 연료를 공급합니다
✍️ 위 내용을 모두 종합해서 ES6 방법으로 써보면
class Car{
constructor(brand, name, color){
this.brand = brand;
this.name = name;
this.color = color;
}
refuel(){
return this.name + '에 연료를 공급합니다'
}
drive(){
return this.name + '가 운전을 시작합니다'
}
}
let genesis = new Car('hyundai', 'genesis', 'black');
let mini = new Car('bmw', 'mini', 'white');
let stinger = new Car('kia', 'stinger', 'blue');
genesis.brand // 'hyundai'
genesis.drive() // '제네시스가 운전을 시작합니다'
class syntax
에서의 상속물려주는 클래스를 부모 클래스
, 물려받는 클래스를 자식 클래스
라고 한다.
extends
와 super
키워드를 이용해서 상속받을 수 있다.