ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • JS 편 - 8일차
    개발 공부/생활코딩! HTML+CSS+JavaScript 2025. 5. 16. 09:00
    반응형



     

    8일차

     

     

     


    33. 객체의 활용

    • 기존에 작성하던 코드를 객체로 마무리하는 시간이다.
    • 완성된 코드는 아래와 같다.
    <!--3.html-->
    <!DOCTYPE html>
    <html>
        <head>
            <title>WEB1 - JavaScript</title>
            <meta charset="utf-8">
            <link rel="stylesheet" href="style.css">
            <script>
                var Links = {
                    setColor:function (color){
                        var alist = document.querySelectorAll('a');
                        var i = 0;
                        while(i < alist.length){
                            alist[i].style.color = color;
                            i = i + 1;
                        }
                    }
                }
                var Body = {
                    setColor:function (color){
                        document.querySelector('body').style.color = color;
                    },
                    setBackgroundColor:function (color){
                        document.querySelector('body').style.backgroundColor = color;
                    }
                }
                function nightDayHandler(self) {
                    var target = document.querySelector('body');
                    if(self.value === 'night') {
                        Body.setBackgroundColor('black');
                        Body.setColor('white');
                        self.value = 'day';
    
                        Links.setColor('powderblue');
                    } else {
                        Body.setBackgroundColor('white');
                        Body.setColor('black');
                        self.value = 'night';
        
                        Links.setColor('blue');
                    }
                }
            </script>
        </head>
        <body>
            <h1><a href="index.html">WEB</a></h1>
            <input type="button" value="night" onclick="
                nightDayHandler(this);
            ">
            <div id="grid">
                <ol>
                    <li><a href="1.html">HTML</a></li>
                    <li><a href="2.html">CSS</a></li>
                    <li><a href="3.html">JavaScript</a></li>
                </ol>
                <div id="article">
                    <h2>JavaScript</h2>
                    <p>
                        JavaScript, often abbreviated JS, is a programming language that is one of the core technologies of the World Wide Web, alongside HTML and CSS.[11] Over 97% of websites use JavaScript on the client side for web page behavior,[12] often incorporating third-party libraries.[13] All major web browsers have a dedicated JavaScript engine to execute the code on users' devices.
                        JavaScript is a high-level, often just-in-time compiled language that conforms to the ECMAScript standard.[14] It has dynamic typing, prototype-based object-orientation, and first-class functions. It is multi-paradigm, supporting event-driven, functional, and imperative programming styles. It has application programming interfaces (APIs) for working with text, dates, regular expressions, standard data structures, and the Document Object Model (DOM).
                        The ECMAScript standard does not include any input/output (I/O), such as networking, storage, or graphics facilities. In practice, the web browser or other runtime system provides JavaScript APIs for I/O.
                        JavaScript engines were originally used only in web browsers, but are now core components of some servers and a variety of applications. The most popular runtime system for this usage is Node.js.
                        Although Java and JavaScript are similar in name, syntax, and respective standard libraries, the two languages are distinct and differ greatly in design.
                    </p>
                </div>                          
            </div>
        </body>
    </html>
    • 먼저 Body라는 객체를 만들어 기존 코드의 target이라고 정의한 변수를 사용하는 코드를 객체화하였다. 이 객체에는 프로퍼티가 하나이상으로, 각각의 프로퍼티를 구분하기 위해 콤마( , )를 사용한다.
    • 그리고 <a>태그를 담은 배열인 alist 변수를 Links라는 객체에 담았다.
    • 이로써 우리도 함수를 객체에 담아 사용할 수 있게 되었다.
    • 그리고 지금까지 사용해온 document.querySelector()에서 document가 객체였고, querySelector()는 함수이며, 객체에 소속되어 있기 때문에 메서드라는 사실을 알게 되었다.
    • 이제 더 이상 우리가 모르는 코드는 없을 것이다. 기본적인 문법 자체는 대부분 알게 되었으며, 이제는 익숙해지고 다양한 것을 써볼 일만 남았다.

     

     


     

     

     

     

    34. 파일로 쪼개서 정리 정돈하기

    • 이전 장에 정리 정돈 도구인 함수와 객체를 배웠다.
    • 이번 장에서는 이것보다 더 큰 정리 정돈 도구를 살펴볼 텐데 서로 연관된 코드들을 파일로 묶어서 그루핑하는 것이다.
    • 우선 지금까지 작업한 야간 모드, 주간 모드를 전환하는 버튼을 다른 페이지인 1.html, 2.html, index.html에 적용해야 한다. 우선 <input>태그를 적용한다.
    <input type="button" value="night" onclick="
        nightDayHandler(this);
    ">
    • 버튼은 생겼지만 자바스크립트는 배포하지 않아서 동작하지 않는다. 모든 페이지에 script 코드를 복사해서 배포하면 잘 동작할 것이다. 하지만 극단적으로 생각하여 이러한 페이지가 1억 개라면 어떻게 될까? 배포가 어려울 것이며, 그러한 것보다 script 코드중 수정할 사항이 있다면 더욱 더 어려워 질 것이다.
    • 이러한 상황을 해결하는 도구가 파일로 쪼개는 것이다.
    • 먼저 colors.js라는 파일을 만들고 3.html에 작성한 <script>태그안의 내용을 colors.js에 붙여넣는다. <script>태그는 제외한다.
    var Links = {
        setColor:function (color){
            var alist = document.querySelectorAll('a');
            var i = 0;
            while(i < alist.length){
                alist[i].style.color = color;
                i = i + 1;
            }
        }
    }
    var Body = {
        setColor:function (color){
            document.querySelector('body').style.color = color;
        },
        setBackgroundColor:function (color){
            document.querySelector('body').style.backgroundColor = color;
        }
    }
    function nightDayHandler(self) {
        var target = document.querySelector('body');
        if(self.value === 'night') {
            Body.setBackgroundColor('black');
            Body.setColor('white');
            self.value = 'day';
    
            Links.setColor('powderblue');
        } else {
            Body.setBackgroundColor('white');
            Body.setColor('black');
            self.value = 'night';
    
            Links.setColor('blue');
        }
    }
    • 그리고 1.html, 2.html, 3.html, index.html의 페이지의 <head>태그 안에 아래의 코드를 추가한다.
    <script src="colors.js"></script>
    • 이렇게 대체하면 모든 페이지에서 주/야간 모드 버튼이 동작하는 것을 볼 수 있다.
    • 파일로 쪼개었을 때의 장점은 새로운 파일을 만들면 모든 코드를 복사할 필요 없이 간단하게 colors.js 파일을 새로운 웹 페이지에 포함시키기만 하면 된다는 것이다.
    • 즉, 작성한 코드를 재사용하게 되는 것이며, colors.js 파일을 수정하면 모든 웹 페이지에 동시에 변화가 반영된다. 다시 말해, 유지보수하기에 매우 편리해졌다고 할 수 있다.
    • 그리고 3.html의 script 부분과 2.html의 <script> 부분이 똑같이 colors.js를 포함시켜져 있기 때문에 완전히 같은 로직을 갖고 있음을 확신할 수 있다. 그래서 가독성이 좋아지고, 코드가 훨씬 명확해지며, 코드의 의미를 파일의 이름을 통해 확인할 수 있게 된다.

     

     

     

    • 또한 서로 연관된 코드들을 여러 개의 파일로 쪼개서 웹 페이지에 포함시키면 코드를 정리 정돈하는 효과 또한 얻을수 있다는 것을 기억하자.
    • 그리고 좋은 점이 또 하나있다. 웹 페이지를 로드하면서 웹 페이지에 접속해서 자바스크립트 파일도 다운로드해야 하므로 2번 접속한다. 물론 이것은 좋지 않은 일이지만 이럼에도 더 효율적이다. 왜냐하면 캐시 때문이다.
    • 캐시는 '저장한다'라는 의미인데, 한 번 웹 페이지에서 다운로드된 파일은 웹 브라우저가 보통 컴퓨터에 저장해 놓게되고 다음에 접속할 때 저장된 파일을 읽어서 네트워크를 통하지 않게된다.
    • 서버 입장에서는 훨씬 더 비용을 절감할 수 있고, 사용자 입장에서도 네트워크 트래픽을 절감할 수 있으며, 훨씬 더 빠르게 웹 페이지를 화면에 표시할 수 있다는 효과가 생기기 때문에 이렇게 파일로 쪼개는 것이 월씬 더 효율적이고 돈도, 시간도 적게 드는 방법이다.

     

     

     

     


    해당 글은 [생활코딩! HTML + CSS + 자바스크립트] 책을 토대로 공부한 내용을 기록하기 위하여 작성됨.

     


     

     

     

    반응형

    '개발 공부 > 생활코딩! HTML+CSS+JavaScript' 카테고리의 다른 글

    JS 편 - 9, 10일차  (1) 2025.05.17
    JS 편 - 7일차  (0) 2025.05.15
    JS 편 - 6일차  (1) 2025.05.14
    JS 편 - 5일차  (1) 2025.05.13
    JS 편 - 4일차  (1) 2025.05.12
Designed by Tistory.