2016년 3월 29일 화요일

생성자 함수

생성자함수
    - 객체를 생성하고 객체를 돌려줌
    - 객체를 생성하는 틀 역할
    - new를 붙이면 새로운 객체를 생성한 후에 이를 리턴
  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);  
  21. </script>  

        ① instanceof 키워드
            (생성자 함수에 의해 생성된 함수가 어떤 생성자 함수로 인해 생성되었는지 확인)
  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 instanceof Make); // true  
  21. </script>  

댓글 없음:

댓글 쓰기