객체 지향 프로그래밍
하나의 모델이 되는 청사진를 만들고 그 청사진을 바탕으로 한 객체를 만드는 프로그래밍 패턴
청사진 : class
그 객체 : instance
ES5
function Car(brand, name, color) {
//인스턴스가 만들어질 때 실행되는 코드
}
ES6
class Car() {
constructor(brand, name, color) {
//인스턴스가 만들어질 때 실행되는 코드
}
}
new 키워드를 통해 클래스의 인스턴스를 만들어낼 수 있다
각각의 인스턴스는 Car라는 클래스의 고유한 속성과 메소드를 갖는다 (avante, mini, beetles)
let avante = new Car('hyundai', 'avante', 'black')
let mini = new Car('bmw', 'mini', 'white')
let beetles = new Car('volkswagen', 'beetles', 'red')
속성과 메소드
클래스에 속성과 메소드를 정의하고 인스턴스에서 이용함
클래스 속성
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
}
}
클래스 메소드
ES5
function Car(brand, name, color) { }
Car.prototype.refel = function() {
//연료 공급을 구현하는 코드
}
Car.prototype.drive = function() {
//운전을 구현하는 코드
ES6
class Car() {
constructor(brand, name, color) { }
refuel() {
}
drive() {
}
}
}
인스턴스의 사용
let avante = new Car('hyundai', 'avante', 'black')
avante.color // 'black'
avante.drive() // 아반떼가 운전을 시작합니다
let avante = new Car('bmw', 'mini', 'white')
avante.color // 'white'
avante.drive() // 미니에 연료를 공급합니다
prototype : 모델의 청사진을 만들 때 쓰는 원형 객체
constructor : 인스턴스가 초기화될 때 실행하는 생성자 함수
this : 함수가 실행될 때 해당 scope마다 생성되는 고유한 실행 context new 키워드로 인스 턴스 생성했을 때에는 해당 인스턴스가 바로 this의 값이 됨