객체지향은 하나의 모델이 되는 청사진(blueprint)을 만들고 청사진을 바탕으로 객체를 만드는 프로그래밍 패턴.
청사진을 class, 그리고 그것을 바탕으로 만들어지는 object들을 instance라고 한다.
class를 만드는 문법은 ES6에서 도입, 'class' 키워드를 이용해서 생성하며 함수처럼 선언식, 표현식 모두 가능.
constructor 메서드는 class 로 생성된 객체를 생성하고 초기화하기 위한 특수한 메서드.
"constructor" 라는 이름을 가진 특수한 메서드는 클래스 안에 한 개만 존재할 수 있다.
this는 쉽게말해 인스턴스 객체를 의미,
this에 할당한다는 것은 만들어지는 인스턴스에 brand,name,color를 할당하겠다는 뜻.
class Car{
constructor(brand,name,color){
this.brand = brand;
this.name = name;
this.color = color;
}
drive(){
console.log(this.name + '가 운전을 시작합니다')
}
}
new 연산자를 이용해 객체타입의 인스턴스를 생성.
즉시 생성자 함수가 실행되며,
변수에 클래스의 설계를 가진 새로운 객체, 즉 인스턴스가 할당.
각각의 인스턴스는 클래스의 고유한 속성과 메서드를 갖게 됨.
let avante =new Car('hyundai','avante','black');
avante.color // 'black'
avante.drive() // 'avante'가 운전을 시작합니다.
ES5 vs ES6
//ES5
function Car(brand, name, color){
this.brand=brand;
this.name=name;
this.color=color;
}
Car.prototoype.drive = function{}
//ES6
class Car{
constructor(brand, name, color){
this.brand=brand;
this.name=name;
this.color=color;
}
drive(){}
}