객체를 생성하는 함수
<script>
function createStudent(이름, 국어, 영어, 수학, 과학) {
return {
이름: 이름,
국어: 국어,
영어: 영어,
수학: 수학,
과학: 과학,
getSum() {
return this.국어 + this.영어 + this.수학 + this.과학
},
getAverage () {
return this.getSum() / 4
},
toString() {
return `${this.이름}\t${this.getSum()}점\t${this.getAverage()}점\n`
}
}
}
const students = []
students.push(createStudent('구름',87, 98, 88, 90))
students.push(createStudent('별이',92, 98, 96, 88))
students.push(createStudent('겨울',76, 96, 94, 86))
students.push(createStudent('바다',98, 52, 98, 92))
let output = '이름\t총점\t평균\n'
for(const s of students) {
output += s.toString()
}
console.log(output)
</script>
객체를 하나하나 만들 때보다 오탈자의 위험이 줄어들고, 코드의 양이 줄어들고, 유지보수를 더 쉽게할 수 있습니다.
하지만 getSum, getAverage, toString() 메소드를 생성하므로 기본 자료형보다 무거운 자료형이 여러 번 생성이 되요.
객체를 정의하고 객체를 활용해서 프로그램을 만드는 것을 객체 지향 프로그래밍이라 해요~~ OOP라고 합니다. 클래스와 프로토타입이라는 2가지 문법으로 객체를 효율적으로 만들 수 있게 했습니다. 클래스는 객체를 만들 때 수많은 지원을 하는 대신 많은 제한을 거는 문법이에요. 그 대신 프로토타입은 제한을 많이 하지는 않지만 지원도 별로 하지 않아요.
대부분의 프로그래밍 언어는 클래스 문법을지원합니다. C++, C#, Java, Ruby, Kotlin .... 등등등.. 자바스크립트는 초창기에는 프로토타입을 지원했으나.. 클래스가 시대의 흐름에 승리하자 클래스를 제공하기 시작했습니다.
클래스를 만들어 볼게요.
<script>
class Student {
}
const student = new Student()
const students = [
new Student(),
new Student(),
new Student(),
new Student(),
]
</script>
클래스는 첫 글자를 대문자로 하는것이 국룰입니다. 오류를 발생시키지는 않지만 다들 그렇게 지킵니다.
new Student() 라는 코드를 보면 함수처럼 괄호를 열고 닫는 기호가 있습니다. 이는 객체가 생성될 때 호출되는 생성자라는 함수입니다.
생성자는 클래스를 기반으로 인스턴스를 생성할 때 처음 호출되는 메소드입니다. 따라서 생성자에서는 속성을 추가하는 등 객체의 초기화 처리를 합니다.
<script>
class Student {
constructor (이름, 국어, 영어, 수학, 과학) {
this.이름 = 이름
this.국어 = 국어
this.영어 = 영어
this.수학 = 수학
this.과학 = 과학
}
getSum() {
return this.국어 + this.영어 + this.수학 + this.과학
}
getAverage() {
return this.getSum() / 4
}
toString() {
return `${this.이름}\t${this.getSum()}점\t${this.getAverage()}점\n`
}
}
const students = []
students.push(new Student('구름',87, 98, 88, 90))
students.push(new Student('별이',92, 98, 96, 88))
students.push(new Student('겨울',76, 96, 94, 86))
students.push(new Student('바다',98, 52, 98, 92))
let output = '이름\t총점\t평균\n'
for (const s of students) {
output += s.toString()
}
console.log(output)
</script>