은닉화 / 캡슐화- 12.html

CODEDRAGON Development/JavaScript, jQuery, ...

반응형

   

은닉화 / 캡슐화

   

   

소스 코드

   

  1. <script type="text/javascript">
  2.                 function Rectangle(width, height){
  3.                         //지역변수는 외부에서 호출 불가(은닉화)
  4.                         var width = width;             
  5.                         var height = height;
  6.                         this.getWidth = function(){
  7.                                 return width;
  8.                         };
  9.                         this.getHeight = function(){
  10.                                 return height;
  11.                         };
  12.                          
  13.                         this.setWidth = function(width){
  14.                                 //검증
  15.                                 if(width < 0){
  16.                                         alert('음수를 입력할 없습니다.');
  17.                                 }else{
  18.                                         width = width;
  19.                                 }
  20.                                  
  21.                         };
  22.                         this.setHeight = function(height){
  23.                                 //검증
  24.                                 if(height < 0){
  25.                                         alert('음수를 입력할 없습니다.');
  26.                                 }else{
  27.                                         height = height;
  28.                                 }
  29.                         };
  30.                 }
  31.                  
  32.                 Rectangle.prototype.getArea = function(){
  33.                         return this.getWidth() * this.getHeight();
  34.                 };
  35.                  
  36.                 var rectangle = new Rectangle(6, 8);           
  37.                 document.write('AREA = ' + rectangle.getArea() + '<br>');
  38.                  
  39.                 rectangle.setWidth(-5);
  40.                 document.write('AREA = ' + rectangle.getArea()+ '<br>');                         
  41.            
  42. </script>
  43. </head>
  44. <body>
  45.    
  46. </body>


   

 

출력결과

   

   

   

   

   

   

   

   

   

반응형

'Development > JavaScript, jQuery, ...' 카테고리의 다른 글

try~catch- 14.html  (0) 2015.03.09
13.html-은닉화 / 캡슐화  (0) 2015.02.01
프로토타입을 사용한 메소드 생성- 11.html  (0) 2015.01.14
prototype 확인- 21.html  (0) 2015.01.04
배열에 객체 저장- 10.html  (0) 2014.12.28