본문 바로가기

프로그래밍/자바스크립트

[자바스크립트]상속

1. 상속

- 자바스크립트는 프로토타입을 이용하여 상속을 구현

 

2. instanceof 연산자

- 생성자 함수를 통해 만들어진 객체 : 인스턴스

- 해당 객체가 어떤 생성자 함수를 통해 생성됐는지 확인할 때 사용

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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>상속</title>
<script type="text/javascript">
/*
 자바스크립트는 프로토타입을 이용하여 상속을 구현
 */
 
     function Human(age){
        this.age = age;
    }
    Human.prototype.type='사람';
    Human.prototype.getType=function(){
        return this.type;
    };
    Human.prototype.getAge = function(){
        return this.age;
    };
    
    var human = new Human(20);
    document.write('human.type = ' + human.type + '<br>');
    document.write('human.age = '+human.age + '<br>');
    document.write('human.getType() = '+human.getType()+'<br>');
    document.write('human.getAge() = ' + human.getAge() + '<br>');
    document.write('=====================================================<br>');
 
    function Student(age){
        this.age = age;
    }
    
    //상속
    Student.prototype = Human.prototype;    //Student.prototype = new Human();  -->으로도 상속 가능
    //프로토타입을 이용하여 상속 시 생성자 함수명이 부모의 생성자 함수명으로 교체되는 현상이 일어난다.
    Student.prototype.constructor = Student;    //생성자명 바꿔준다.
    
    //객체 생성
    var student = new Student(40);
    document.write('student.type = ' + student.type + '<br>');
    document.write('student.getType() = ' + student.getType() + '<br>');
    document.write('studnet.getAge() = ' + student.getAge() + '<br>');
    
    //생성자명을 변경해서 student.constructor = function Student(age){ this.age = age; } 라고 나옴
    //생성자명을 변경안해주면 student.constructor = function Human(age){ this.age = age; } 라고 나온다.
    document.write('student.constructor = ' + student.constructor + '<br>');
    
    document.write('=====================================================<br>');
    
    //해당 객체가 어떤 함수를 통해 생성되었는지 확인할 때 instranceof 키워드를 사용
    document.write((student instanceof Student)+'<br>');    //student는 Student를 통해 생성되었으니 true
    document.write((student instanceof Human) + '<br>');    //student는 Student를 통해 생성되었고, Student는 Human의 자식객체이므로 true
    document.write((student instanceof Object+ '<br>');    //true
    document.write((student instanceof Number+ '<br>');    //false
    
    
</script>
//출력결과
human.type = 사람
human.age = 20
human.getType() = 사람
human.getAge() = 20
=====================================================
student.type = 사람
student.getType() = 사람
studnet.getAge() = 40
student.constructor = function Student(age){ this.age = age; }
=====================================================
true
true
true
false
</head>
<body>
 
</body>
</html>
cs