상속- 15.html

CODEDRAGON Development/JavaScript, jQuery, ...

반응형

   

상속

   

자바스크립트에서는 프로토타입을 이용한 상속을 이용해서 상속작업을 수행

   

   

소스 코드

   

  1. <script type="text/javascript">
  2. /* 자바스크립트에서는 프로토타입을 이용한 상속을 이용해서 상속작업을 수행 */
  3.         function Human(age){
  4.         //프로퍼티  = 지역변수
  5.         this.age = age;
  6.         }
  7.          
  8.         //프로토타입이 상속되어 그래서 자바스크립트의 상속을 프로토타입 상속이라고
  9.         Human.prototype.type = '인간';
  10.         Human.prototype.getType = function(){
  11.                 return this.type;
  12.         };
  13.         Human.prototype.getAge = function(){
  14.                 return this.age;
  15.         };
  16.          
  17.         var human = new Human(30);
  18.         document.write('human.type: ' + human.type + '<br>');
  19.         document.write('human.age: ' + human.age + '<br>');
  20.         document.write('human.getType(): ' + human.getType() + '<br>');
  21.         document.write('human.getAge(): ' + human.getAge() + '<br>');
  22.          
  23.          
  24.         document.write('<br>상속 ===============================<br>');
  25.         function Student(age){
  26.                 this.age = age;        
  27.         }
  28.         //상속
  29.         //getType(), getAge() 상속됨
  30.         Student.prototype = Human.prototype;
  31.         //Student.prototype = new Human();      //동일 표현
  32.          
  33.         //프로토타입의 생성자를 재정의(정의하지 않아도 구동상의 문제는 없음)
  34.         Student.prototype.constructor = Student;
  35.          
  36.         var student = new Student(50);
  37.         document.write('student.type: ' + student.type + '<br>');
  38.         document.write('student.age: ' + student.age + '<br>');
  39.         document.write('student.getType(): ' + student.getType() + '<br>');
  40.         document.write('student.getAge(): ' + student.getAge() + '<br>');
  41.          
  42.          
  43.         document.write('<br>상속 관계 확인===============================<br>');
  44.         //instanceof
  45.         document.write( (student instanceof Student) + '<br>');
  46.         document.write( (student instanceof Human) + '<br>');
  47.         document.write( (student instanceof Object) + '<br>');
  48.         document.write( (student instanceof Number) + '<br>');
  49.          
  50. </script>
  51. </head>
  52. <body>
  53.    
  54. </body>


   

   

출력결과

   

   

   

반응형