2016년 3월 30일 수요일

프로토타입 기반 언어

프로토타입 기반 언어
동적으로 객체의 구조와 동작 방식을 바꿀 수 있는 장점이 있지만, 클래스 기반 언어보다 정확성, 안정성, 예측가능성이 떨어진다.

  1. <script>    
  2.     function Make(name, top, bottom, color) {    
  3.         this.name = name;    
  4.         this.top = top;    
  5.         this.bottom = bottom;    
  6.         this.color = color;    
  7.             
  8.         this.print = function() {    
  9.             var out='';    
  10.             out+='name:'+this.name+'\n';    
  11.             out+='top:'+this.top+'\n';    
  12.             out+='bottom:'+this.bottom+'\n';    
  13.             out+='color:'+this.color;    
  14.                 
  15.             console.log(out);    
  16.         }    
  17.     }    
  18.         
  19.     var clothes = new Make('suit', 100, 32, 'black');    
  20.     console.log(clothes.hasOwnProperty('color'));  
  21. </script>   
    * 객체에 hasOwnProperty() 함수가 구현되어 있지 않으나 정상 작동


           1) 프로토타입(prototype)
             - 속성과 메서드 포함, 객체
             - 모든 객체는 자신의 프로토타입을 가리키는 prototype라는 숨겨진 속성을 가짐
             - 모든 객체는 속성을 상속하는 프로토타입 객체에 연결됨
             - 표기법({ })을 이용하여 생성된 객체는 Javascript의 표준 객체인 Object의 속성
               인 프로토타입(Object.prototype) 객체에 연결
             - 객체 생성 시 결졍된 프로토타입 객체는 다른 객체로 변경 가능


            2) 생성자 함수를 이용한 객체 생성 시 프로토타입
  1. <script>    
  2.     function Make(name, top, bottom, color) {    
  3.         this.name = name;    
  4.         this.top = top;    
  5.         this.bottom = bottom;    
  6.         this.color = color;    
  7.             
  8.         this.print = function() {    
  9.             var out='';    
  10.             out+='name:'+this.name+'\n';    
  11.             out+='top:'+this.top+'\n';    
  12.             out+='bottom:'+this.bottom+'\n';    
  13.             out+='color:'+this.color;    
  14.                 
  15.             console.log(out);    
  16.         }  
  17.           
  18.         Make.prototype.alertMsg = function() {  
  19.             alert('');  
  20.         }  
  21.     }    
  22.         
  23.     var clothes = new Make('suit', 100, 32, 'black');    
  24.     clothes.alertMsg();  
  25. </script>    


            3) 프로토타입 체이닝
               - 프토로타입 체인     상위의 프로토타입 객체들과 연결된 프로토타입
                                           링크들의 집합
               - 프로토타입 체이닝  프로토타입 체인을 따라 상위 프로토타입 객체를
                                           차례로 검색하는 행위



댓글 없음:

댓글 쓰기