프로토타입을 사용한 메소드 생성- 11.html

CODEDRAGON Development/JavaScript, jQuery, ...

반응형

프로토타입을 사용한 메소드 생성

   

   

학습내용

(중요)프로토타입은

  • 생성자 함수를 사용해 생성된 객체가 공통으로 가지는 공간
  • prototype영역 호출
  • 메모리 영역의 효율성 증가
  • 상속에서도 동일한 개념이 나옴

   

   

소스 코드

   

  1. <script type="text/javascript">
  2.         function Student(name, korean, math, english, science){
  3.                 this.name = name;
  4.                 this.korean = korean;
  5.                 this.math = math;
  6.                 this.english = english;
  7.                 this.science = science;
  8.         }
  9.          
  10.         //프로토타입은 생성자 함수를 사용해 생성된 객체가 공통으로 가지는 공간
  11.         //prototype영역 호출
  12.         //메모리 영역의 효율성 증가
  13.         Student.prototype.getSum = function(){
  14.                 return this.korean + this.math + this.english + this.science;
  15.         };
  16.         Student.prototype.getAverage = function(){
  17.                 return this.getSum()/4;
  18.         };
  19.         Student.prototype.toString = function(){
  20.                 return this.name + ', ' + this.getSum() + ', ' + this.getAverage();
  21.         };
  22.          
  23.          
  24.         var students = [];
  25.         students.push(new Student('홍길동', 99, 88, 55, 66));
  26.         students.push(new Student('일지매', 99, 77, 67, 78));
  27.         students.push(new Student('대장금', 45, 65, 65, 87));
  28.         students.push(new Student('금잔디', 99, 88, 55, 66));
  29.         students.push(new Student('하회탈', 99, 88, 55, 66));
  30.         students.push(new Student('곰탱이', 99, 80, 55, 66));
  31.          
  32.         //출력
  33.         var output = '이름, 총점, 평균\n';
  34.         for(var i in students){
  35.                 output += students[i].toString() + '\n';
  36.         }
  37.         alert(output);
  38. </script>
  39. </head>
  40. <body>
  41.    
  42. </body>


 

   

출력결과

   

반응형