► 하나의 모델이 되는 청사진을 만들고, (class)
그 청사진을 바탕으로 한 객체(Object)를 만드는 instance) 프로그래밍 패턴
function Car (brand, name, color) {
//인스턴스가 만들어질 때 실행되는 코드
}
class Car() {
constructor(brand, name, color) {
//인스턴스가 만들어질 때 실행되는 코드
}
}
► new 키워드를 통해 클래스의 인스턴스를 만들어낼 수 있습니다.
let avante = new Car('hyundai', 'avante', 'black');
let mini = new Car('bmw', 'mini', 'white');
let beetles = new Car('volkswagen', 'beetles', 'red');
각각의 인스턴스는 Car라는 클래스의 고유한 속성과, 메소드를 갖습니다
► 속성과 메소드
클래스에 속성과 메소드를 정의하고, 인스턴스에서 사용합니다
위와 같이 객체 지향 프로그래밍은, 현실 세계를 기반으로 프로그래밍 모델을 만들때에 유용합니다
► 클래스: 속성의 정의
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.refuel = function() {
// 연료 공급을 구현하는 코드
}
Car.prototype.drive = function() {
// 운전을 구현하는 코드
}
ES6
class Car() {
constructor(brand, name, color) {/* 생략 */}
retuel() {
}
drive() {
}
}
► 인스턴스에서의 사용 예시
ES5
function Car(brand, name, color) {
this.brand = brand; //이 예시에서 this는 avante와 mini를 의미함
this.name = name;
this.color = color;
}
let avante = new Car('hyundai', 'avante', 'black');
let mini = new Car('bmw', 'mini', 'white');
avante.color // black;
avante.name // avante;
mini.brand // bmw;
Car.prototype.drive = function () {
console.log(this.model + '출발!');
}
avante.drive(); // avante출발!!
mini.drive(); // mini출발!!
► prototype? constructor? this?
► 요약
// 이 함수는 constructor(생성자)함수
// Car === class
function Car(brand, name, color) {
this.brand = brand; //this 객체 : 이 예시에서 this는 avante와 mini를 의미함
this.name = name;
this.color = color;
}
// Car.prototype = prototype 객체 : 여기에 속성이나 메소드를 정의할 수 있음
Car.prototype.drive = function () {
console.log(this.name + '가 운전을 시작합니다');
}
//여기서 avante === instance
let avante = new Car('hyundai', 'avante', 'black');