쌓고 쌓다

[JavaScript] 클래스 (+객체) 본문

프로그래밍/JavaScript

[JavaScript] 클래스 (+객체)

승민아 2023. 1. 8. 13:48

먼저, 클래스를 사용하지 않고 객체를 생성하여 사용하는 방법들을 보이겠다.

 

객체 배열 생성

const students = []
students.push({이름: '홍길동', 국어: 10, 영어: 10})
students.push({이름: '철수', 국어: 20, 영어: 20})

console.log(JSON.stringify(students, null, 2))

students 배열에 객체들을 넣었다.

 

객체 배열 조회

let output = '이름\t국어\t영어\n'

for(const s of students) {
    output += `${s.이름}\t${s.국어}\t${s.영어}\n`
}

console.log(output)

 

객체를 처리하는 함수 선언 및 출력

function getSumOf(student) {
    return student.국어 + student.영어
}

function getAvgOf(student) {
    return getSumOf(student)/2
}

let output = '이름\t총점\t평균\n'
for(const s of students) {
    output += `${s.이름}\t${getSumOf(s)}점\t${getAvgOf(s)}점\n`
}

템플릿 리터럴에 ${getSumOf(s)}처럼 함수 호출의 결과를 출력할 수도 있다.

 

객체에 메소드 추가

for(const s of students) {
    s.getSumOf = function() {
        return this.국어 + this.영어
    }
}

output = '이름\t총점\n'
for(const s of students) {
    output += `${s.이름}\t${s.getSumOf(s)}\n`
}

객체마다 메소드를 추가할 수 있다.

앞에 작성한 객체를 처리하는 함수를 선언하여 사용한다면 함수 이름이 충돌할 수도 있고, 매개변수에 어떤 종류의 객체를 넣어야 하는지 알기 힘들어 잘못 사용할 수 있다.

하지만 이렇게 객체에 메소드를 추가하면 함수 이름의 충돌을 방지할 수 있고, 함수를 잘못 사용하는 경우 방지 가능하다.

 

객체를 함수로 생성

function createStudent(이름, 국어, 영어) {
    return {
        이름: 이름,
        국어: 국어,
        영어: 영어,
        
        getSum() {
            return this.국어 + this.영어
        },
        getAvg() {
            return this.getSum()/2
        }
    }
}

const students = []
students.push(createStudent('홍길동', 10, 10))
students.push(createStudent('철수', 20, 20))

객체를 손쉽게 만들 수 있다는 장점이 있으나

객체별로 getSum, getAvg 메소드를 만들기 때문에 함수보다 무거운 자료형이 여러 개 생성된다.

(객체에 소속된 함수를 메소드라 부르고, 객체에 속하지 않는 것을 함수라고 부른다.)

 

 

위의 방법들로 객체를 생성하기보단 더 효율적인 방법으로 생성하고자 해서 클래스가 도입되었다.

 


클래스 선언

클래스 선언

class 클래스이름 {
   ...
}

클래스는 객체를 만드는 함수와 비슷한것으로 객체를 생성하기 위한 틀로 보면 된다.

 

객체 생성

new 클래스이름()

객체는 클래스를 통해 생성된 것이다. 붕어빵 틀에서 만들어진 붕어빵으로 보면 된다.

 

클래스 선언 및 객체 생성

// 클래스 선언
class Student {

}

// 학생 생성
const student = new Student()

// 학생 리스트 생성
const students = [
    new Student(),
    new Student(),
    new Student()
]

 

클래스 생성자

class 클래스이름 {
    constructor() {
        /* 생성자 코드 */
    }
}

객체가 생성될때 호출되는 함수이다.

메소드 이름을 constructor이라고 지었지만 constructor라는 이름으로 사용하는 것이 아닌

new Student()처럼 그냥 클래스 선언할때 사용한 이름으로 호출한다.

자바에서는 클래스 이름과 동일하게 메소드 이름을 작성했지만 차이가 있다.\

 

생성자를 이용해 객체를 생성해보자.

class Student {
    constructor(이름, 국어, 영어) {
        this.이름 = 이름
        this.국어 = 국어
        this.영어 = 영어
    }
}

const students = []
students.push(new Student('홍길동', 10, 10))
students.push(new Student('철수', 20, 20))

 

클래스 메소드

class Student {
    constructor(이름, 국어, 영어) {
        this.이름 = 이름
        this.국어 = 국어
        this.영어 = 영어
    }
    
    getSum() {
        return this.국어 + this.영어
    }
    
    getAvg() {
        return this.getSum()/2
    }
}

메소드 사이에 쉼표는 넣지 않는다.

 

마지막으로 클래스를 사용해 출력해 보자.

const students = []
students.push(new Student('홍길동', 10, 10))
students.push(new Student('철수', 20, 20))

output = '이름\t총점\t평균\n'
for(const s of students) {
    output += `${s.이름}\t${s.getSum()}\t${s.getAvg()}\n`
}

console.log(output)

 

Comments