1 분 소요

함수(Function)

<!--ex9.html-->
<ul>
    <script>
        function two() {
            document.write('<li>2-1</li>');
            document.write('<li>2-2</li>');
        }
        document.write('<li>1</li>');
        two();
        document.write('<li>3</li>');
        two();
    </script>
</ul>

반복되지만 연속되지 않는 것은 반복문으로 표현이 어렵다. 그래서 함수로 바꾼다! function은 함수를 만드는 키워드

매개변수(Parameter)와 인자(Argument)

<!--ex9.html-->
<script>
    function onePlusOne() {
        document.write(1+1+'<br>'); // 2
    }
    onePlusOne();
    function sum(left, right) {
        document.write(left + right + '<br>')
    }
    sum(2, 3); // 5
    sum(3, 4); // 7
</script>

함수를 정의하는 과정에서 쓰는 변수는 매개변수(parameter), 함수를 넘길 때 쓰는 값은 인자(argument)

리턴(Return)

<!--ex9.html-->
<script>
    function sum2(left, right) {
        return left + right;
    }
    document.write(sum2(2,3) + '<br>');
    document.write('<div style="color: red">'+ sum2(2,3) + '</div><br>');
    document.write('<div style="font-size: 3rem">'+ sum2(2,3) + '</div><br>');
</script>

return을 통해 계산된 값을 ‘원자화’하여 사용할 수 있다. 즉 반환값의 색을 바꾸거나 폰트 사이즈를 크게 바꿀 수도 있다.

버튼 개선

이전 포스팅에서 조건문과 토글을 통해 만든, 반복문과 배열을 통해 개선한 버튼을, 함수로 또 개선해보자

// 토글 코드 개선4: 함수

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';
            console.log(alist[i]);
            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';
            console.log(alist[i]);
            i = i + 1;
        }
    }
}

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

함수 nightDayHandler()의 기본 매개변수는 self, 인자는 this라는 키워드를 사용한다.

개선 전과 기능은 같지만, 유지보수가 한결 더 편해졌다!

출처: [생활코딩!HTML+CSS+자바스크립트 JS편 Chapter 24~28]

태그:

카테고리:

업데이트: