개념:
1) 데이터와 기능을 한 곳에 묶어서 처리
2) 속성과 메소드가 하나의 '객체'라는 개념에 포함
클래스(Class)라는 이름:
"청사진"을 바탕으로 한 객체는 인스턴스 (instance), 청사진은 클래스(class)
construntor (인스턴스가 초기화될때 실행되는 함수)
class Car {
constructor(brand, name, color) {
this.brand = brand;
this.name = name;
this.color = color;
}
} // this? (함수 실행 시, 해당 scope 마다 생성되는 고유한 실행 context
// new 키워드로 인스턴스 생성할 시, 해당 인스턴스가 this의 값
let avante = new Car('hyundai', 'avante', 'black')
객체 지향 프로그램의 네 가지 특징
1) 캡슐화:
데이터 기능의 느슨한 결합. 구현(데이터)은 숨기는 기능을 노출시킴(은닉화). 설정하는 함수(setter), 불러오는 함수(getter)를 철저하게 나누기.
2) 상속:
부모-자식 관계처럼 부모의 특징을 자식이 보유함.
3) 추상화:
실제 사용자에게 메소드는 숨기고 단순한 이름으로 정의함.
4) 다형성:
프로토타입
모든 객체들이 메소드와 속성들을 상속 받기 위한 템플릿으로써 프로토타입 객체(prototype object)를 가진다. 상속되는 속성과 메소드들은 각 객체가 아니라 객체의 생성자의 prototype이라는 속성에 정의되어 있다. (MDN)
extends
와 super
키워드를 이용해서 상속을 구현한다.class Person {
constructor(first, last, age, gender, interests) {
this.name = {
first,
last
};
this.age = age;
this.gender = gender;
this.interests = interests;
}
greeting() {
console.log(`Hi! I'm ${this.name.first}`);
};
farewell() {
console.log(`${this.name.first} has left the building. Bye for now!`);
};
}
let han = new Person('Han', 'Solo', 25, 'male', ['Smuggling']);
han.greeting();
// Hi! I'm Han
let leia = new Person('Leia', 'Organa', 19, 'female' ['Government']);
leia.farewell();
// Leia has left the building. Bye for now
! extends
주목 !
class Teacher extends Person {
constructor(first, last, age, gender, interests, subject, grade) {
this.name = {
first,
last
};
this.age = age;
this.gender = gender;
this.interests = interests;
// subject and grade are specific to Teacher
this.subject = subject;
this.grade = grade;
}
}
! super
주목 !
class Teacher extends Person {
constructor(first, last, age, gender, interests, subject, grade) {
super(first, last, age, gender, interests);
// subject and grade are specific to Teacher
this.subject = subject;
this.grade = grade;
}
}
let snape = new Teacher('Severus', 'Snape', 58, 'male', ['Potions'], 'Dark arts', 5);
snape.greeting(); // Hi! I'm Severus.
snape.farewell(); // Severus has left the building. Bye for now.
snape.age // 58
snape.subject; // Dark arts