최신글
hyeonga_code
JSON_02_JSON 표기법_프로토타입을 사용한 자바스크립트 클래스 생성 본문
반응형
- 프로토타입을 사용한 자바스크립트 클래스 생성
- 기본적으로 제공하고 있는 클래스 외에 추가적으로 새로운 클래스를 정의할 수 있습니다.
'클래스 이름' = function('매개 변수') {
....
}
- 객체 생성
var '변수 이름' = new '클래스 이름'( '매개 변수');
- 클래스가 제공할 함수를 정의할 때에 prototype을 사용합니다.
'클래스 이름'.prototype.'함수 이름' = function('매개 변수') {
....
}
- 함수 호출
var '변수 이름' = new '클래스 이름'( '매개 변수');
'변수 이름'.'함수 이름'('매개 변수');
- 리턴값이 있는 경우 변수에 담아 사용할 수 있습니다.
- 새로운 Dynamic Web Project를 생성합니다.
- webapp > prototype 폴더를 생성합니다.
- prototype > 'log.js' javascript 파일을 생성합니다.
=====
1
2
3
4
5
6
7
8
9
10
11
|
/**
*
*/
function log(msg){
var console = document.getElementById("debugConsole");
if(console != null){
console.innerHTML += msg + "<br>";
}
}
|
- prototype > 'member.js' javascript 파일을 생성합니다.
=====
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
|
/**
*
*/
Member = function(name, id, securityNo){
this.name = name;
this.id = id;
this.securityNo = securityNo;
}
Member.prototype.setValue = function(newName, newId, newSecurityNo){
this.name = newName;
this.id = newId;
this.securityNo = newSecurityNo;
}
Member.prototype.getAge = function(){
var birthYear = parseInt(this.securityNo.substring(0, 2));
var code = this.securityNo.substring(6, 7);
if(code == '1' || code == '2'){
birthYear += 1900;
} else if(code == '3' || code == '4'){
birthYear += 2000;
}
var today = new Date();
return today.getFullYear() - birthYear;
}
Member.prototype.toString = function() {
return this.name + "[" + this.id + "]";
}
|
- prototype > 'useMember.html' html 파일을 생성합니다.
=====
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
|
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>useMember.html</title>
<script type="text/javascript" src="log.js"></script>
<script type="text/javascript" src="member.js"></script>
<script type="text/javascript">
window.onload = function() {
var mem = new Member("nameValue 01", "idValue 01", "7000001000000");
log("Before change--");
log("Name : " + mem.toString());
log("Age : " + mem.getAge());
mem.setValue("nameValue 02", "idValue 02", "8000001000000");
log("After change--");
log("Name : " + mem.toString());
log("Age : " + mem.getAge());
}
</script>
</head>
<body>
<div id="debugConsole">
<!-- 출력 위치입니다. -->
</div>
</body>
</html>
|
- useMember.html 파일을 실행합니다.
반응형
'JSON' 카테고리의 다른 글
JSON_07_JSON 표기법 응답 생성 시 주의할 점 (0) | 2023.10.28 |
---|---|
JSON_05_자바스크립트에서 패키지 정의하기 (0) | 2023.10.28 |
JSON_04_JSON 표기법 (0) | 2023.10.27 |
JSON_03_Object 를 사용한 개별 객체에 프로퍼티 확장하기 (0) | 2023.10.27 |
JSON_01_JavaScript Object Notation이란? (0) | 2023.10.26 |