1. 프로토타입
- 생성자 함수를 사용해 생성된 객체가 공통으로 가지는 공간
- 객체를 생성할 때마다 동일한 함수를 계속 생성하는 것은 메모리 낭비이므로 프로토타입을 이용해 공통으로 사용할 메서드를 지정
- 객체명.prototype.함수명 = function(){};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
|
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>프로토타입 사용한 메서드 생성</title>
<script type="text/javascript">
function Student(name, korean, english, math){
this.이름 = name;
this.국어 = korean;
this.영어 = english;
this.수학 = math;
}
//객체명.prototype.함수명
//Student.prototype.getSum = function(){};
//프로토타입임을 알려줌. 함수명
Student.prototype.getSum = function(){
return this.국어 + this.영어 + this.수학;
};
Student.prototype.getAverage = function(){
return this.getSum()/3;
};
Student.prototype.toString = function(){
return this.이름 + ', ' + this.getSum() + ', ' + this.getAverage();
};
var students = [];
students.push(new Student('홍길동',100,99,93));
students.push(new Student('박문수',99,98,94));
students.push(new Student('강호동',98,97,95));
students.push(new Student('김유신',80,96,96));
students.push(new Student('장영실',81,95,97));
students.push(new Student('이순신',82,94,98));
//출력
var output = '이름, 총점, 평균<br>';
for(var i in students){
output += students[i].toString() + '<br>';
}
document.write(output);
</script>
//출력결과
이름, 총점, 평균
홍길동, 292, 97.33333333333333
박문수, 291, 97
강호동, 290, 96.66666666666667
김유신, 272, 90.66666666666667
장영실, 273, 91
이순신, 274, 91.33333333333333
</head>
<body>
</body>
</html>
|
cs |
'프로그래밍 > 자바스크립트' 카테고리의 다른 글
[자바스크립트] DOM : getElementsByTagName(), getElementById(), getElementsByName(), getElementsByClassName() (0) | 2021.07.27 |
---|---|
[자바스크립트]상속 (0) | 2021.07.27 |
[자바스크립트]객체 : 생성자 함수를 이용한 객체 생성 및 활용 (0) | 2021.07.27 |
[자바스크립트]객체 : 배열에 객체 저장 (0) | 2021.07.27 |
[자바스크립트]객체 : toString (0) | 2021.07.27 |