
클래스와 인스턴스에 대해
class 는 설계도와 같다. instance 설계도를 바탕으로 각각의 특정한 자동차 모델과 같다.
일반적인 함수를 정의하듯 객체를 만들면 되는데 new 키워드를 써서 새로운 instance 를 만든다.
class 문법은 ES6(ECAMScript 6)에 도입 되어 비교적 최근에 사용되기 시작했다.
//ES5
function Car(brand, name, color){
//인스턴스가 만들어질 때 실행되는 코드
}
//ES6
class Car {
constructor(brand, name, color){
// 인스턴스가 만들어질 때 실행되는 코드
}
}
객체지향 프로그래밍에서 생성자(constructor) 함수를 사용한다. 인스턴스가 만들어질 때 실행되는 코드다.
생성자 함수는 return 값을 만들지 않는다.
let avante = new Car('hyundai', 'avante', 'black');
let sorento = new Car('kia', 'sorento', 'white');
// new 키워드를 사용하여 인스턴스를 만든다. 각각의 인스턴스는 Car라는 클래스의 고유한 속성과 메서드를 갖는다.
클래스에 속성과 메서드를 정의하며, 인스턴스에 이용한다. 위코드를 빗대어 속성과 매서드를 어떻게 나뉠 수 있을까?
자동차에 대한 Class 이기 때문에 속성에는 브랜드 , 색상, 차 이름, 최고 속력 등이 있을 수 있고
매서드를 생각해보면 속력 설정, 운전 등의 행동하는 무언가를 지정하는 느낌으로 보면 될 것 같다.
// ES5
function Car(brand, name, color){
this.brand = brand;
this.name = name;
this.color = color;
}
// ES6
class Car{
constrctor(brand, name, color){
this.brand = brand;
this.name = name;
this.color = color;
}
}
클래스 사용시 this 라는 새로운 키워드가 등장한다. this 는 인스턴스 객체를 의미한다. parameter 로 넘어온 값을
인스턴스 생성 시 지정하는 값이다.
// ES5
function Car(brand, name, color){
this.brand = brand;
this.name = name;
this.color = color;
}
Car.prototype.refuel = function(){
// 연료 공급을 구현하는 코드
}
Car.prototype.drive= function(){
// 운전을 구현하는 코드
}
// ES6
class Car{
constrctor(brand, name, color){
this.brand = brand;
this.name = name;
this.color = color;
}
refuel(){
}
drive(){
}
}
ES5에서는 prototype이라는 키워드를 사용해야 메서드를 정의할 수 있다. ES6에서는 생성자 함수(constrctor)와 함께
안쪽 class 키워드 안쪽에 묶어서 정의한다.
// 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가 운전을 시작합니다.'
// 위코드를 class 키워드를 이용하여 바꿔보면
// ES6
class Car{
constrctor(brand, name, color){
this.brand = brand;
this.name = name;
this.color = color;
}
drive(){
console.log(`${this.name}가 운전을 시작합니다.`)
}
}