16-Class
1. 클래스(class)
생성자 함수는 ‘붕어빵 기계’처럼 객체를 찍어낼 수 있는 ‘템플릿’ 양식 같은 개념이고,객체는 템플릿을 통해 데이터를 주입해서 만든 ‘붕어빵’에 비유할 수 있습니다.
이것이 가능한 이유는 JavaScript에서는 프로토타입(Prototype)을 토대로 해서 객체지향 프로그래밍을 지원해주기 때문입니다.
대다수 객체 지향 언어들은 프로토타입보다 클래스(Class)를 기반으로 동작합니다.
JavaScript의 내부에서는 프로토타입을 쓰고, 개발자들은 클래스를 이용해도 내부에서는 프로토타입을 이용하기 때문입니다.
참고로 ES6+ 이상의 JavaScript에서 Class 문법을 지원합니다. 그리고 현업의 대부분 언어는 클래스를 사용하고, 생성자 함수를 더 이상 사용하고 있지 않습니다.
💡 용어 정리
클래스(Class): 객체를 생성할 수 있는 템플릿 (e.g. 청사진, 틀, 양식, 설계도)
- 특정 객체(인스턴스)를 생성하기 위한 변수와 메소드(함수)를 정의하는 틀
객체지향 프로그래밍(Object-Oriented Programming): 객체끼리 서로 호환되도록 프로그래밍하는 것인스턴스(Instance): 클래스를 통해 객체를 만들 수 있는데, 이때 클래스를 이용해 만들어진 객체들
javascript
1// 객체를 손쉽게 만들수 있는 템플릿2// 1. 생성자 함수 (오래된 고전적인 방법)3// 2. 클래스 ✨4class Fruit {5// 모든 클래스는 기본 생성자(constructor)가 존재해야 함6// 생성자: new 키워드로 객체를 생성할때 호출되는 함수7constructor(name, emoji) {8this.name = name9this.emoji = emoji10}1112display = () => {13console.log(`${this.name}: ${this.emoji}`)14}15}1617const apple = new Fruit('apple', '🍎') // apple은 Fruit 클래스의 인스턴스이다.18const orange = new Fruit('orange', '🍊') // orange은 Fruit 클래스의 인스턴스이다.1920console.log(apple) // Fruit { display: [Function: display], name: 'apple', emoji: '🍎' }21console.log(orange) // Fruit { display: [Function: display], name: 'orange', emoji: '🍊' }22console.log(apple.name)23console.log(apple.emoji)24apple.display()2526// obj는 객체이고, 그 어떤 클래스의 인스턴스도 아니다.27const obj = { name: 'ellie' }
cf. MDN Class
2. 재사용성을 높이는 방법(static)
클래스에 정의된 프로퍼티와 메서드는 인스턴스 레벨의 프로퍼티와 메서드라고 합니다.
왜냐하면 클래스에서 정의한 프로퍼티와 함수들이 인스턴스에 중복적으로 만들어지기 때문입니다.
각각의 인스턴스들을 통해 객체.속성 또는 객체.함수로 호출할 수 있습니다.
모든 객체마다 동일하게 참조해야 하는 속성이나 함수가 있다면, 클래스 레벨의 프로퍼티와 메서드를 사용하면 됩니다.
클래스 안에 static 키워드를 프로퍼티나 메서드 앞에 작성하면, 만들어진 인스턴스에 포함되지 않고 클래스에 그대로 남아있게 됩니다. 즉, 클래스에 1번만 정의하고 인스턴스에서 재사용을 하는 것입니다.
그래서 호출할 때도만들어진 인스턴스.이 아니라 클래스명.으로 클래스 레벨의 메서드를 호출할 수 있습니다.
javascript
1// static 정적 프로퍼티, 메서드2class Fruit {3static MAX_FRUITS = 44// 생성자: new 키워드로 객체를 생성할때 호출되는 함수5constructor(name, emoji) {6this.name = name7this.emoji = emoji8}910// 클래스 레벨의 메서드11static makeRandomFruit() {12// 클래스 레벨의 메서드에서는 this를 참조할 수 없음13return new Fruit('banana', '🍌')14}1516// 인스턴스 레벨의 메서드17display = () => {18console.log(`${this.name}: ${this.emoji}`)19}20}2122const banana = Fruit.makeRandomFruit()23console.log(banana) // Fruit { display: [Function: display], name: 'banana', emoji: '🍌' }24console.log(Fruit.MAX_FRUITS) // 42526// apple은 Fruit 클래스의 인스턴스이다.27const apple = new Fruit('apple', '🍎')28// orange은 Fruit 클래스의 인스턴스이다.29const orange = new Fruit('orange', '🍊')3031console.log(apple) // Fruit { display: [Function: display], name: 'apple', emoji: '🍎' }32console.log(orange) // Fruit { display: [Function: display], name: 'orange', emoji: '🍊' }33console.log(apple.name)34console.log(apple.emoji)35apple.display()3637Math.pow() // math 클래스 API38Number.isFinite(1) // number 클래스 API
3. 필드(field)
javascript
1// 접근제어자 - 캡슐화2// private(#), public(기본), protected3class Fruit {4// # : 내부에서는 사용 가능, 외부에서는 사용 불가5#name6#emoji7#type = '과일'8constructor(name, emoji) {9this.#name = name10this.#emoji = emoji11}12#display = () => {13console.log(`${this.#name}: ${this.#emoji}`)14}15}1617const apple = new Fruit('apple', '🍎')18// apple.#name = '오렌지'; // #field는 외부에서 접근이 불가능함19console.log(apple) // Fruit {}
4. getter와 setter
javascript
1// 접근자 프로퍼티 (Accessor Property)2class Student {3constructor(firstName, lastName) {4this.firstName = firstName5this.lastName = lastName6}78/*** Getter의 역할9* 1) 데이터를 가공해서 새로운 데이터를 반환할떄10* 2) private한 값을 반환할 떄11*/12// fullName에 접근(호출)할 떄13get fullName() {14return `${this.lastName} ${this.firstName}`15}1617/*** Setter의 역할18* 프로퍼티를 priavte로 만들면 직접 접근이 불가능하다.19* 이럴 떄, Setter로 값을 변경한다.20* Setter는 많이 사용되지 않는다.21*/22// fullName에 할당할 떄23set fullName(value) {24console.log('set', value)25}26}2728const student = new Student('수지', '김')29student.firstName = '안나'30console.log(student.firstName) // 안나31console.log(student.fullName) // 김 안나32student.fullName = '김철수' // set 김철수
5. 상속(inheritance)-super
super키워드 : 부모의 기능을 그대로 유지하면서 추가적인 기능을 하고 싶을 때
javascript
1class Animal {2constructor(color) {3this.color = color4}5eat() {6console.log('먹자!')7}8sleep() {9console.log('잔다')10}11}1213class Tiger extends Animal {}14const tiger = new Tiger('노랑이')15console.log(tiger) // Tiger { color: '노랑이' }16tiger.sleep() // 잔다17tiger.eat() // 먹자!1819class Dog extends Animal {20constructor(color, ownerName) {21super(color)22this.ownerName = ownerName23}24play() {25console.log('놀자아~!')26}2728// 오버라이딩 overriding29eat() {30super.eat() // 부모의 기능을 그대로 유지하면서 추가적인 기능을 하고 싶을 떄31console.log('강아지가 먹는다!')32}33}3435const dog = new Dog('빨강이', '엘리')36console.log(dog) // Dog { color: '빨강이', ownerName: '엘리' }37dog.sleep() // 잔다38dog.eat() // 먹자! 강아지가 먹는다!39dog.play() // 놀자아~!