개발나라 스용공주

[생활코딩] JavaScript 왕기초 10장 - Visual Studio Code / 함수의 활용 - 리팩토링에 함수 이용하기 본문

WEB/JavaScript

[생활코딩] JavaScript 왕기초 10장 - Visual Studio Code / 함수의 활용 - 리팩토링에 함수 이용하기

스용공주 2024. 9. 2. 18:24
728x90
728x90

이번 글은 아래 강의 내용을 바탕으로 작성되었습니다.

(생활코딩)

https://www.youtube.com/watch?v=WsPJ8FsoMcU&list=PLuHgQVnccGMBB348PWRN0fREzYcYgFybf&index=28

 


 

[ 세부 설명 ]

코드가 정상적으로 실행되지 않는 이유에 대한 풀이이다.

전체 코드에 대한 내용은 아래에 작성되어져 있다.

 

아래 코드는 <body> 바깥에 nightButton()이라는 함수를 만들어준 부분이다.

function nightButton() {
            var target = document.querySelector('body');
            var list = document.querySelectorAll('a');
            var i = 0;
            if(this.value == 'night') {
                target.style.backgroundColor = 'black';
                target.style.color = 'white';
                while(i < list.length) {
                    list[i].style.color = 'lavender';
                    i += 1;
                }
                this.value = 'day'; }
            else {
                target.style.backgroundColor = 'white';
                target.style.color = 'black';
                while(i < list.length) {
                    list[i].style.color = 'purple';
                    i += 1;
                }
                this.value = 'night'; }
                }

 

아래 코드는 <body> 안에서 위에서 만든 nightButton() 함수를 사용해준 것이다.

위와 아래 코드를 보면 함수의 형태는 function 함수명() {함수내용}; 과 같은 형태로 만들어준 뒤 함수명();로 함수를 사용할 수 있다는 것을 확인할 수 있다.

<input type = "button" value = "night" onclick="
        nightButton();
">

 

 

이렇게 작성하면 함수의 전체적인 틀에서 틀린 부분은 없다.

그런데 이 코드는 원활하게 실행되지 않는다.

 

그 이유는 바로 아래 코드와 같이 함수를 만들고 함수내용을 선언하면서 this를 사용하였기 때문이다.

=> if(this.value == 'night')와 같이 this를 사용

if(this.value == 'night') {
                target.style.backgroundColor = 'black';
                target.style.color = 'white';
                while(i < list.length) {
                    list[i].style.color = 'lavender';
                    i += 1;
                }
                this.value = 'day'; }

 

 

분명 함수로 묶어주기 전에는 this가 <input>태그 안에서 잘 사용되었는데 왜 이제는 오류가 나는지 확인해보면 이유는 다음과 같다.

this의 속성은 this가 써져있는 태그 자체를 가리키는 것이다.

하지만 지금 함수로 묶으면서 this가 있는 위치(태그)를 변경해주었기 때문에 타깃 지점이 변경된 것이 이유이다.

 

그렇다면 매개변수(parameter)와 인수(argument)를 통해 타깃 경로를 따라갈 수 있도록 해줘야한다.

방법은 아래와 같다.

먼저, self라는 매개변수를 사용하여 this가 가리키는 곳들을 다 임시적으로 매개변수 self로 채워둔다.

그럼 이제 매개변수 self는 this가 가리키는 모든 영역을 가리키게 된다.

function nightButton(self) {
            var target = document.querySelector('body');
            var list = document.querySelectorAll('a');
            var i = 0;
            if(self.value == 'night') {
                target.style.backgroundColor = 'black';
                target.style.color = 'white';
                while(i < list.length) {
                    list[i].style.color = 'lavender';
                    i += 1;
                }
                self.value = 'day'; }
            else {
                target.style.backgroundColor = 'white';
                target.style.color = 'black';
                while(i < list.length) {
                    list[i].style.color = 'purple';
                    i += 1;
                }
                self.value = 'night'; }
                }

 

그리고 이제 매개변수 self로 this가 사용될 영역들을 모두 대신 표시해뒀기 때문에 self에 this가 사용되야되는 것을 표시하기 위해 nightButton() 함수가 사용되는 부분에 인자를 this로 넣어주어 해당 영역에서 사용된 nightButton() 함수는 this가 매개변수로 들어가지도록 해준다.

<input type = "button" value = "night" onclick="
        nightButton(this);
">

 

 

 


 

[ 수정 전 전체 코드 ]

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title></title>
    <style>
    </style>
    <script>
        function nightButton() {
            var target = document.querySelector('body');
            var list = document.querySelectorAll('a');
            var i = 0;
            if(this.value == 'night') {
                target.style.backgroundColor = 'black';
                target.style.color = 'white';
                while(i < list.length) {
                    list[i].style.color = 'lavender';
                    i += 1;
                }
                this.value = 'day'; }
            else {
                target.style.backgroundColor = 'white';
                target.style.color = 'black';
                while(i < list.length) {
                    list[i].style.color = 'purple';
                    i += 1;
                }
                this.value = 'night'; }
                }
    </script>
</head>
<body>
    <input type = "button" value = "night" onclick="
        document.querySelector('body').style.backgroundColor = 'black';
        document.querySelector('body').style.color = 'white';
    ">
    <input type = "button" value = "day" onclick="
    document.querySelector('body').style.backgroundColor = 'white';
    document.querySelector('body').style.color = 'black';
    ">
    <input type = "button" value = "night" onclick="
        nightButton();
    ">

    안녕하세요<br>
    <a href="https://www.youtube.com/watch?v=1pBoUsMzqZE"><u>Youtube Link 1</u></a><br>
    <a href="https://www.youtube.com/watch?v=1pBoUsMzqZE"><u>Youtube Link 2</u></a><br>
    <a href="https://www.youtube.com/watch?v=1pBoUsMzqZE"><u>Youtube Link 3</u></a><br>
    <a href="https://www.youtube.com/watch?v=1pBoUsMzqZE"><u>Youtube Link 4</u></a><br>
    <a href="https://www.youtube.com/watch?v=1pBoUsMzqZE"><u>Youtube Link 5</u></a>
</body>
</html>

 

 

[ 수정 후 전체 코드 ]

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title></title>
    <style>
    </style>
    <script>
        function nightButton(self) {
            var target = document.querySelector('body');
            var list = document.querySelectorAll('a');
            var i = 0;
            if(self.value == 'night') {
                target.style.backgroundColor = 'black';
                target.style.color = 'white';
                while(i < list.length) {
                    list[i].style.color = 'lavender';
                    i += 1;
                }
                self.value = 'day'; }
            else {
                target.style.backgroundColor = 'white';
                target.style.color = 'black';
                while(i < list.length) {
                    list[i].style.color = 'purple';
                    i += 1;
                }
                self.value = 'night'; }
                }
    </script>
</head>
<body>
    <input type = "button" value = "night" onclick="
        document.querySelector('body').style.backgroundColor = 'black';
        document.querySelector('body').style.color = 'white';
    ">
    <input type = "button" value = "day" onclick="
    document.querySelector('body').style.backgroundColor = 'white';
    document.querySelector('body').style.color = 'black';
    ">
    <input type = "button" value = "night" onclick="
        nightButton(this);
    ">

    안녕하세요<br>
    <a href="https://www.youtube.com/watch?v=1pBoUsMzqZE"><u>Youtube Link 1</u></a><br>
    <a href="https://www.youtube.com/watch?v=1pBoUsMzqZE"><u>Youtube Link 2</u></a><br>
    <a href="https://www.youtube.com/watch?v=1pBoUsMzqZE"><u>Youtube Link 3</u></a><br>
    <a href="https://www.youtube.com/watch?v=1pBoUsMzqZE"><u>Youtube Link 4</u></a><br>
    <a href="https://www.youtube.com/watch?v=1pBoUsMzqZE"><u>Youtube Link 5</u></a>
</body>
</html>

 

 

 


 

728x90
728x90
Comments