6.7 함수를 사용한 객체 생성
객체를 하나씩 직접 만들어 배열에 넣으면 서로 다른 형태의 객체를 배열 안에 넣을 수 있다는 장점이 있지만, 번거럽고, 어려우며 시간이 오래 걸린다. 이런 과정을 쉽게 하기 위하여 하나의 '틀'을 만드는 함수를 만들어 매개변수를 받아 객체를 만든 후 객체를 리턴시킨다.
객체를 생성하는 함수의 기본형식(1)
function makeStudent(name, korean, math, english, science) { var willReturn = { }; return willReturn; }
객체를 생성하는 함수의 기본형식(2)
function makeStudent(name, korean, math, english, science) { var willReturn = { //속성 이름: name, 국어: korean, 수학: math, 영어: english, 과학: science, //메서드 getSum: function () { return this.국어 + this.수학 + this.영어 + this.과학; }, getAverage: function () { return this.getSum() / 4; }, toString: function () { return this.이름 + '\t' + this.getSum() + '\t' + this.getAverage(); } }; return willReturn; }
makeStudent()함수를 생성해서 객체를 찍어내듯이 생산할 수 있다.
function makeStudent(name, korean, math, english, science) { /*생략*/ } //학생정보 배열 생성 var students = []; students.push(makeStudent('홍길동', 87, 99, 100, 50)); students.push(makeStudent('홍갑동', 85, 92, 80, 90)); students.push(makeStudent('홍상동', 86, 93, 90, 80)); students.push(makeStudent('홍정동', 83, 90, 10, 60)); //출력 var output = '이름\t총정\t평균\n'; for (var i in students) { output += students[i].toString() + '\n'; } console.log(output);












