하나의 모델이 되는 청사진(blueprint)를 만들고,
그 청사진을 바탕으로 한 객체(object)를 만드는 프로그래밍 패턴을
객체 지향 프로그래밍 이라고한다.
여기서 하나의 모델이 되는 청사진을 -> class
청사진을 바탕으로 한 객체 -> instance
우선 class를 만드는 두가지 방법이있다.
->
// 함수를 사용한 방식
function Car(name, brand, price) {
this.name = name;
this.brand = brand;
this.price = price;
}
Car.prototype.refuel = function() {
}
->
// 클래스 생성자를 이용한 방식
class Car{
constructor(name,brand,price){
this.name = name;
this.brand = brand;
this.price = price;
}
refuel() {
}
}
정리해보면 청사진(blueprint)이 함수이고 class 이다.
constructor는 인스턴스가 초기화될 때 실행하는생성자 함수이다.
위의 클래스 생성자를 이용한 방식을 사용한 클래스를 보면
class Car{
constructor(name,brand,price){
this.name = name;
this.brand = brand;
this.price = price;
}
refuel() {
}
}
// class 를 바탕으로 한 객체는 -> instance
let user1Car = new Car('sportage','KIA','4000만원')
// user1Car = {name: 'sportage', brand: 'KIA', price: '4000만원'}
user1Car가 instance 이다.
this 키워드가 등장하는데 this는 인스턴스 객체를 의미한다.