1. 

<script type="text/javascript">

var students = [];

students.push({

name:'john',

kor:100,

eng:100

});

students.push({

name:'tom',

kor:90,

eng:90

});

students.push({

name:'mike',

kor:80,

eng:100

});

</script>

; 개별적으로 객체를 만드는 것은 반복적인 행위를 하는 것이다.


아래와 같이 변경해서

<script type="text/javascript">

function makeStudent(name,kor, eng){

var willReturn = {

name : name,

kor : kor,

eng : eng,

//method

getSum:function(){

return this.kor + this.eng;

},

getAvg:function(){

return this.getSum() / 2;

},

toString : function(){

return this.name + '\t' + this.getSum() + '\t' + this.getAvg();

}

};

return willReturn;

}

var students = [];

students.push(makeStudent('john', 100, 100) );

students.push(makeStudent('tom', 100, 80) );

students.push(makeStudent('mike', 70, 100) );

var output ="이름\t총점\t평균\n";

for( var i in students ){

output += students[i].toString() + "\n";

}

alert(output);

</script>





; 생성자함수와 동일하다. 



+ Recent posts