정의:
하나의 모델이 되는 청사진을 만들고 -> class로 생각
그 청사진을 바탕으로 한 객체(object)를 만드는 프로그래밍 패턴 -> class로 만들어진 instance
나만의 추상화: Class는 청사진 역할을 하는 존재로서 인스턴스를 찍어내는 공장
클래스 특징:
class Car
class Movie
this
라는 키워드 필요 -> 인스턴스 객체에 들어올 속성을 부여해줌/* ES5 class 작성 */
function Car(brand, name, color) {
// 인스턴스가 말들어질 때 실행되는 코드
// 속성 부여, this는 instance가 생성될 시의 속성을 지칭
this.brand = brand;
this.name = name;
this.color = color;
}
// 함수(method) 생성 방법
Car.prototype.refuel = function() {
}
Car.prototype.refule = function() {
}
ES6에서는 생성자 함수(constructor)
로 class 작성
/* ES6의 class 키워드*/
class Car {
// 생성자 함수{}
constructor (brand, name, color) {
// 인스턴스가 만들어질 때 실행되는 코드
// 속성 부여, this는 instance가 생성될 시의 속성을 지칭
this.brand = brand;
this.name = name;
this.color = color;
}
// (protype 기재 없는)힘수(method) 생성
refuel() {
}
drive() {
}
}
나만의 추상화: 공장(class)에서 세부사항(속성)을 넣어 생산된 제품(instance)
인스턴스
new
라는 키워드를 이용하여 생성new
가 불려옴에 따라 class안에 있는 생성자함수 새로운 instance를 만들어 냄/* 인스턴스 생성 */
let avante = new Car ('hyundai', 'avante', 'black');
avante.color; // black
avante.drive(); // 운전시작 함수