기본 콘텐츠로 건너뛰기

javascript 캡슐화


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<script>
        //생성자 함수를 선언
        function Retangle(width, height) {
            this.width = width;
            this.height = height;
        }
        Retangle.prototype.getArea = function () {
            return this.width * this.height;
        };
        //변수 선언
        var rectangle = new Retangle(57);
        alert('AREA : ' + rectangle.getArea());
    </script>

cs
생성자 함수 Rectangle선언


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<script>
        //생성자 함수를 선언
        function Retangle(width, height) {
            this.width = width;
            this.height = height;
        }
        Retangle.prototype.getArea = function () {
            return this.width * this.height;
        };
        //변수 선언
        var rectangle = new Retangle(57);
        rectangle.width = -2;
        alert('AREA : ' + rectangle.getArea());
    </script>
cs
잘못된 속성의 사용

길이에는 음수가 나올수 없는데 음수 값을 출력을 내게 된다.

캡슐화란 이렇게 잘못 사용될 수 있는 객체의 특정 부분을 사용자가 직접 사용할 수 없게 막는 기술
또한 만일의 상황을 대비해서 특정 속성이나 메서드를 사용자가 사용할 수 없게 숨겨놓는 것
캡슐화를 구현할때 클로저를 활용을 한다.



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
<script>
        //생성자 함수를 선언
        function Retangle(w, h) {
            //변수를 선언.
            var width = w; //this가 아닌 var로 변수 선언 외부 접근에서 못함
            var height = h;
            //메서드를 선언
            this.getWidth = function () { return width; };
            this.getHeight = function(){return height;};
            this.setWidth = function (w) { width = w; };
            this.setHeight = function (h) { height = h; };
        }
        Retangle.prototype.getArea = function () {
            return this.width * this.height;
        };
        //변수 선언
        var rectangle = new Retangle(57);
      
        alert('AREA : ' + rectangle.getArea());
    </script>
cs
cs
이제 외부에서는 width와 height를 직접 사용할 수 없고 
get과 set을 이용하여 width와 height를 접근을 할 수 있다.



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
 <script>
        //생성자 함수를 선언
        function Retangle(w, h) {
            //변수를 선언.
            var width = w;
            var height = h;
            //메서드를 선언
            this.getWidth = function () {
                return width;
            };
            this.getHeight = function () {
                return height;
            };
            this.setWidth = function (w) {
                if (w < 0throw '길이는 음수일 수 없다';
                else width = w;
            };
            this.setHeight = function (h) {
                if (h < 0throw '길이는 음수일 수 없다';
                else height = h;
            };
        }
        Retangle.prototype.getArea = function () {
            return this.getHeight() * this.getWidth();
        };
        //변수 선언
        var rectangle = new Retangle(5,7);
        rectangle.setHeight(2);
        alert('AREA : ' + rectangle.getArea());
    </script>
cs
throw는 오류창을 띄어주는 놈

길이가 0이하로 가면 throw를 이용하여 에러창을 띄운다




댓글

이 블로그의 인기 게시물

[node.js] 파일 리더기 만들기 - 사용 모듈 정리, pdf 구조, hwp 구조

pdf -> html 변환 가장 무난하다. 기본적으로 pdf는 htm와 비슷한 형태의 구조를 가지고 있다. 크게 header , body , xref table , trailer 의 구조로 되어있다. pdf는 환경에 상관없이 표현을 하기 위한 목적을 가지고 있는 파일이다. 이런 이유 때문에 무난히 진행이 된 것 같다. pdf2htmlex와 pdftohtmljs라는 모듈을 이용을 했다. var pdftohtml = require ( 'pdftohtmljs' ) ; var converter = new pdftohtml ( 'test.pdf' , "sample.html" ) ; converter . convert ( 'ipad' ) . then ( function ( ) { console . log ( "Success" ) ; } ) . catch ( function ( err ) { console . error ( "Conversion error: " + err ) ; } ) ; 이미지나, text같은 것들이 거의 100%로 변환이 된다. docx -> html 변환 docx파일을 html파일로 변환을 할 때는 style 적용과 한글이 깨지는 문제가 있다. 텍스트들을 전부 잘 읽기는 하는데 스타일 정보를 제대로 가져오지 못하기 때문에 좀 애매하다 - Headings. - Lists. - Customisable mapping from your own docx styles to HTML. For instance, you could convert WarningHeading to h1.warning by providing an appropriate style ...

[css] css로 프린트 방지하기

웹에서 프린트 제어가 불가능 한 줄 알았는데 프린트 클릭 시  스크립트로 해당 이벤트를 받아올 수 있다. 하지만 스크립트를 사용하는 방법은 브라우저마다 작동을 하지 않을 수 있다. 좀 더 찾아보니 css로 인쇄되는 영역을 제어를 해줄 수 있다.  @media print 를 이용하면 된다. < html > < head > < title > print test page < / title > < style > @media print { . np { display : none ; } } < / style > < / head > < body > < div class = "np" > test < / div > < div > test1 < / div > < div > test1 < / div > < div > test1 < / div > < / body > < / html > 위 코드를 보면 np 클래스를 @media print에 넣어주었다. @media print는 인쇄됐을 때의 스타일을 지정을 해주는 것이다.  위에서는 해당 페이지를 인쇄할 때 p를 display : none으로 가려주었다. @media print를 이용하면 좀 더 멋진 인쇄물을 만들 수 ...

[알고리즘] snake게임 알고리즘

막무가네로 알고리즘을 공부하면 재미가 없으니 게임을 접목하여 다루어 보도록 하겠습니다. 게임의 대상은 스네이크 게임입니다. 많은 사람들은 어릴 때 뱀게임을 많이 해봤을 것 입니다. 이번에 다뤄볼 주제는 뱀이 움직임을 어떻게 구현을 할지 알아보겠습니다. 뱀은 크게 3가지의 경우가 있습니다 1. 가장 중요한 뱀을 움직이기 2. 음식먹기 이때 뱀은 크기가 늘어나야 합니다. 3. 뱀이 움직이는 정책   - 뱀이 움직이지 못하는 경우는 : 우측방향에서 좌측 방향으로 OR 위에 아래 방향고 같이 180도 반전되는 움직임은 막겠습니다. 순수한 알고리즘을 만드는 과정이기 때문에 음식을 먹었는지 안먹었는지 판단하는 부분은 랜덤으로 판단을 하도록 하겠습니다. def is_eat(): return random.choice([1, 0]) 랜덤으로 1, 0을 반환을 해줍니다. 실제로 게임을 만든다면 해당 함수는 뱀의 머리가 음식의 좌표와 같은지 검사를 해주면 되겠습니다. key_position_map = { 'w': [-1, 0], # up 's': [1, 0], # down 'a': [0, -1], # left 'd': [0, 1] # right } direction = key_position_map.get('d') 다음으로는 키맵핑을 한 오브젝트 입니다. direction은 현재 뱀의 방향을 나타냅니다. snake_body = [[2, 3], [1, 3],[1, 2], [1, 1]] 주인공이 되는 뱀의 좌표들 입니다. while True: key = input() new_direction = key_position_map.get(key) if new_direction and direction_check(direction, new_direction): directi...