/**
* 📌 객체 지향 프로그래밍이란?
* 하나의 모델이 되는 청사진을 만들고, 그 청사진을 바탕으로 한 객체를 만드는 프로그래밍 패턴이다.
*
* 🔎
* 메서드 - 메서드란 "객체에 딸린 함수" 이다.
* prototype - prototype 이란 "모델의 청사진을 만들 때 쓰는 원형 객체(original form)" 입니다.
* constructor - "인스턴스가 초기화될 때 실행하는 생성자 함수"
* this - "함수가 실행될 때, 해당 scope마다 생성되는 고유한 실행 context(execution context)
* new 키워드로 인스턴스를 생성했을 때에는, 해당 인스턴스가 바로 this의 값이 됨"
*/
// 1️⃣ 클래스 만들기(ES6 클래스 작성 문법!)
// 1. 대문자로 시작
// 2. constructor(생성자 함수) 사용 -> 인스턴스가 초기화될 때 실행하는 생성자 함수
// 3. this는 클래스로 만들어진 인스턴스 를 의미
class Car {
constructor(brand, name, color) {
this.brand = brand;
this.name = name;
this.color = color;
}
refuel() {
// 메서드
console.log('주유중입니다.');
}
drive() {
// 메서드
console.log('주행중입니다.');
}
}
// 2️⃣ 인스턴스 - 클래스(청사진)을 바탕으로 만듬
// 인스턴스 생성 - 1. new 키워드 사용
let avante = new Car('hyundai', 'avante', 'black');
console.log(avante.brand); // hyundai
avante.drive(); // 주행중입니다.
let spark = new Car('쉐보레', '스파크', '흰색');
console.log(spark.brand); // 쉐보레
spark.refuel(); // 주유중입니다.
// 📌 클래스의 예제
// 우리가 그동안 사용했던 배열은, 전부 Array의 인스턴스이다!
let grandure = new Car('hyundai', 'grandure', 'black');
console.log(grandure.name); // grandure
grandure.drive(); // 주행중입니다.
let arr = ['code', 'states', 'pre'];
arr.length;
console.log(arr.push('course')); // 4 -> push()의 리턴값은 length
// 속성이나 메서드 사용법이 동일한 것을 볼 수 있다.
let arr2 = new Array('code', 'states', 'pre');
arr2.length;
console.log(arr2.push('course')); // 4
// mdn문서를 보면 메서드들이 대부분 Array.prototype.메서드명 과 같이 안내되있다.
// 이는 모든 메서드들이 클래스의 원형 객체(prototype)에 정의되어 있기 때문이다.
// 📌 class 문법을 이용한 카운터 만드는 실습
class Counter {
constructor() {
this.value = 0; // // 생성자 호출을 할 경우, this는 new 키워드로 생성한 Counter의 인스턴스입니다
}
increase() {
this.value++;
}
decrease() {
this.value--;
}
getValue() {
return this.value;
}
}
let counter1 = new Counter(); // 생성자 호출
counter1.increase();
console.log(counter1.getValue()); // 1
// 📌 ES5 클래스 작성 문법! - 생성자 함수
function Car2(brand, name, color) {
this.brand = brand;
this.name = name;
this.color = color;
}
Car.prototype.refuel = function () {
// 연료 공급을 구현하는 코드
};
Car.prototype.drive = function () {
// 운전을 구현하는 코드
};