모던 자바스크립트 핵심가이드 - 12. 클래스

2022. 2. 15. 14:39혼자하는개발공부/JavaScript

CHAPTER 12 클래스

클래스: 클래스는 일차적으로 자바스크립트의 기존 프로토타입 기반 상속에 대한 문법적 설탕이다. 클래스 문법이 자바스크립트에 새로운 객체 지향 상속 모델을 도입하는 것은 아니다.

12.1 클래스 생성

클래스를 만드는 방법 두가지 : 1) 클래스 선언 2) 클래스 표현식

//클래스 선언
class Person {

}

//클래스 표현식
const person = class Person {
};
class Person {
    constructor(name, age){
        this.name = name;
        this.age = age;
    }
    greet(){
        console.log(`Hi, my name is ${this.name} and I'm ${this.age} years old`);
    }
    // 메소드와 메소드 사이에는 쉼표가 없음
    farewell(){
        console.log("goodbye friend");
    }
}

const yerin = new Person("yerin", 21);

yerin.greet();
//Hi, my name is yerin and I'm 21 years old
yerin.farewell();
//goodbye friend

12.2 정적 메서드

클래스 자체에서 접근할 수 있는 정적 메소드는 다음과 같이 정의할 수 있다.

class Person{
    constructor(name, age){
        this.name = name;
        this.age = age;
    }
    static info(){
        console.log("I Want to go home, hello");
    }
}

const minji = new Person("minji", 20);
minji.info();
//Uncaught TypeError: minji.info is not a function at <anonymous>:12:7
Person.info();
//I Want to go home, hello

12.3 set와 get

getter및 setter 메서드를 사용하여 클래스 내에 값을 설정하거나 가져올 수 있다.

class Person {
    constructor(name, surname){
        this.name = name;
        this.surname = surname;
        this.nickname = "";
    }
    set nicknames(value){
        this.nickname = value;
        console.log(this.nickname);
    }
    get nicknames(){
        console.log(`your nickname is ${this.nickname}`);
    }
}

const yerin = new Person("yerin", "kim");

// 세터를 호출
yerin.nicknames = "rin";
// "rin";

// 게터를호출
yerin.nicknames;
//your nickname is rin

12.4 클래스 상속하기

class Person {
    constructor (name, age){
        this.name = name;
        this.age = age;
    }
    greet(){
        console.log(`Hi, my name is ${this.name} and I'm ${this.age} years old`);
    }
}

// 상속을 통해 만든 새 클라스
class Adult extends Person {
    constructor(name, age, work){
        super(name, age);
        this.work = work;
    }
}

const alberto = new Adult("alberto", 13, "student");

console.log(alberto.age);
console.log(alberto.work);
alberto.greet();

Adult는 Person 클래스의 모든 속성과 메소드를 상속했음을 볼 수 있다.

12.5 배열 확장하기

class Classroom extends Array {
    // 레스트 연산자를 사용해 가변 인수로 입력받은 학생들의 정보를
    // 배열 형태로 students에 할당
    constructor(name, ...students){
        // 스프레드 연산자를 사용해 배열 원소들을 다시 풀어헤쳐 생성자를 호출한다.
        // 스프레드 연산자를 사용하지 않으면
        // '학생들의 정보가 들어 있는 배열'을 원소로 가진 Array가 생성될 것이다.
        super(...students);
        this.name = name;
    }
    // 학생을 추가하기 위한 새로운 메서드를 추가
    add(student){
        this.push(student);
    }
}
const myClass = new Classroom( '1A',
    {name: "Tim", mark: 6},
    {name: "Tom", mark: 3},
    {name: "Jim", mark: 8},
    {name: "Jon", mark: 10},
);

//새로운 학생 추가
myClass.add({name: "Timmy", mark:7});
myClass[4];

// for of 루프를 사용하여 반복 가능
for (const student of myClass){
    console.log(student);
}

배열을 상속받아서 새로운 클래스 만들었음