본문 바로가기

소프트웨어/JavaScript

[JavaScript] 객체 개념 활용 - 야간모드 예제 간결하게

오늘은 객체의 개념을 활용하여 이전까지 만들었던 야간모드 예제 코드를 중복을 더욱 줄이고 수정이 편리한 코드로 만들었다. 

 

 

아래 코드를 보면 if문과 else문에서 "target.style.글자색깔"이 반복되는 것을 알 수 있다. 

코드가 더욱 길어질 경우 글자색깔을 변경하기 어려울 것이다. 중복된 코드를 함수로 독립시키면 편하게 수정 가능하다. 

편하게 수정 하기위해 객체 개념을 이용하여 최대한 반복을 줄여보겠다. 

<!DOCTYPE HTML>
<html>
    <head>
        <title>WEB - JavaScript</title>
        <meta charset="utf-8">
        <script>
            function nightDayHandler(self){
                var target = document.querySelector('body');
                if (self.value ==='night'){
                    target.style.backgroundColor='black';
                    target.style.color='white';
                    self.value ='day';

                    var alist = document.querySelectorAll('a');
                    var i = 0;
                    while(i<alist.length){
                        alist[i].style.color='powderblue';
                        i = i+1;
                    }
                }   
                else { 
                    target.style.backgroundColor='white';
                    target.style.color='black';
                    self.value ='night';

                    var alist = document.querySelectorAll('a');
                    var i = 0;
                    while(i<alist.length){
                        alist[i].style.color='blue';
                        i = i+1;
                    }
                } 
            }      
        </script>
        <link rel ="stylesheet" href="style.css">
    </head>
    <body>
        <h1><a href="index.html">WEB</a></h1>
        <input id ="night_day" type="button" value="night" onclick="
            nightDayHandler(this);
        ">
            <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>
                <h2>JavaScript</h2>
                <p>
                    JavaScript (/ˈdʒɑːvəskrɪpt/), often abbreviated as JS, is a programming language that is one of the core technologies of the World Wide Web, alongside HTML and CSS. As of 2022, 98% of websites use JavaScript on the client side for webpage behavior, often incorporating third-party libraries. 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.[10] 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).
                </p>
            </div >
        </div>
    </body>
</html>

 

 

1. 반복되는 부분을 독립된 함수로 선언

            function setColor(color){
                var alist = document.querySelectorAll('a');
                    var i = 0;
                    while(i<alist.length){
                        alist[i].style.color= color;
                        i = i+1;
                    }
            }

 

2. 함수로 선언한 부분을 삭제하고 함수 호출

            function nightDayHandler(self){
                var target = document.querySelector('body');
                if (self.value ==='night'){
                    target.style.backgroundColor='black';
                    target.style.color='white';
                    self.value ='day';

                    setColor('powderblue');
                }   

                else { 
                    target.style.backgroundColor='white';
                    target.style.color='black';
                    self.value ='night';

                    setColor('blue');
                }
            }

코드 추가

setColor('powderblue'); 

setColor('blue'); 

 

 

3. 객체 안에 함수 호출 

            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;
                }
            }

 

 

4. 2번 코드 객체 성질을 이용하여 출력

           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');
                }
            }

 

 

최종 코드

<!DOCTYPE HTML>
<html>
    <head>
        <title>WEB - JavaScript</title>
        <meta charset="utf-8">
        <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>
        <link rel ="stylesheet" href="style.css">
    </head>
    <body>
        <h1><a href="index.html">WEB</a></h1>
        <input id ="night_day" type="button" value="night" onclick="
            nightDayHandler(this);
        ">
            <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>
                <h2>JavaScript</h2>
                <p>
                    JavaScript (/ˈdʒɑːvəskrɪpt/), often abbreviated as JS, is a programming language that is one of the core technologies of the World Wide Web, alongside HTML and CSS. As of 2022, 98% of websites use JavaScript on the client side for webpage behavior, often incorporating third-party libraries. 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.[10] 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).
                </p>
            </div >
        </div>
    </body>
</html>