ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Javascript] 함수
    Web/Javascript 2020. 5. 16. 04:43

    함수 예고

     

    함수: 코드가 많아지면 그 코드를 잘 정리정돈하기 위한 도구

     

    함수

     

    1. ex9.html 파일 작성

    <!DOCTYPE html>

    <html>

      <head>

        <meta charset="utf-8">

        <title>함수</title>

      </head>

      <body>

        <h1>function</h1>

        <h2>basic</h2>

        <ul>

          <script>

            document.write('<li>1</li>');

            document.write('<li>2-1</li>');

            document.write('<li>2-2</li>');

            document.write('<li>3</li>');

          </script>

        </ul>

        <h2>parameter & argument</h2>

        <h2>return</h2>

      </body>

    </html>

     

     

    2. 2-1, 2-2가 반복되게 하기

          <script>

            document.write('<li>1</li>');

            document.write('<li>2-1</li>');

            document.write('<li>2-2</li>');

            document.write('<li>3</li>');

            document.write('<li>2-1</li>');

            document.write('<li>2-2</li>');

          </script>

     

    반복문을 쓸 수 없는 경우: 연속적으로 반복되는 것이 아니라 연속되지 않게 반복될 때

     

    3. 반복되는 코드를 함수로 만들기

        <ul>

          <script>

        function two() {

                document.write('<li>2-1</li>');

                  document.write('<li>2-2</li>');

        }

            document.write('<li>1</li>');

            document.write('<li>2-1</li>');

            document.write('<li>2-2</li>');

            document.write('<li>3</li>');

            document.write('<li>2-1</li>');

            document.write('<li>2-2</li>');

          </script>

        </ul>

     

    함수가 등장하기 때문에 function을 적고, 함수의 이름을 웹브라우저에게 알려준다. 여기서는 two. 그리고 중괄호 안에 반복되는, 즉 재사용하고 싶은 코드를 붙여넣음.

     

    4. 반복되는 코드를 함수로 바꾸기

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

            document.write('<li>2-1</li>');

            two();

          </script>

        </ul>

     

     

     

    매개변수와 인자

     

    지금까지 살펴본 함수는 자판기에 제품이 하나밖에 없어서 언제나 똑같은 제품을 받을 수 있는 자판기. 원하는 제품을 선택하면 그 제품에 해당하는 제품을 제공하는 자판기가 있다면 훨씬 더 효용이 있을 것.

     

    입력 - 매개변수(parameter 또는 arguement)

    출력 - return

     

    1. 1+1을 출력하는 코드 작성

     

    <script>

        document.write(1+1);

    </script>

     

     

    2.  1+1을 함수로 만들기

     

    <script>

        function oneplusone() {

            document.write(1+1);

        }

        oneplusone();    

    </script>

     

    oneplusone은 언제나 똑같이 동작하는 함수.

    이 함수를 실행할 때 입력값을 주면 그 입력값에 따라 다른 결과를 출력한다면 ->

    예를 들어, sum(2,3); 이라고 했을 때 그 결과가 5가 되게 하고 sum(3,4); 로 해서 함수를 실행했을 때 7이 될 수 있다면?

     

     

    3. 입력값에 따라 다른 결과를 출력하는 함수로 만들기

    <script>

        function oneplusone(){

            document.write(1+1+'<br>');

        }

        oneplusone();

        function sum(left,right){

            document.write(left + right + '<br>');

        }

        sum(2,3); // 5

        sum(3,4); // 7

    </script>

     

    sum(2,3); 과 비교하면 먼저 옆에 있는 sum과 이름이 같음. 그리고 2와 3이라는 값은 위 코드의 괄호 안에 각각 들어있음. 그래서 2에 해당하는 첫 번째 자리에는 left를 쓰고, 3에 해당하는 두 번째 자리에는 right라는 변수를 정의. 바로 이러한 변수를 매개하는 변수라 해서 매개변수라 부름.

    이 코드를 실행하면 left의 값은 2, right의 값은 3이 되도록 약속돼 있음.

    이때 함수로 전달하는 2,3이라는 값을 인자라고 하며 이 값을 받아서 함수 안으로 매개하는 변수가 매개변수.

     

     

    함수(return 문)

     

    1+1은 2에 대한 표현식, 2-1은 1에 대한 표현식, 1===1은 true에 대한 표현식. 함수도 마찬가지

    sum()이라는 함수를 실행하면 document.write(left + right + '<br>');이 실행되겠지만 이번에는 sum()을 실행했을 때 2+3의 계산 결과인 5를 받도록 표현식을 만들 것. 이를 위해서는 return을 알아야 함.

     

    1. 덧셈한 결과를 빨간색으로 출력하는 새로운 함수 sumColorRed()

    <script>

        function oneplusone(){

            document.write(1+1+'<br>');

        }

        oneplusone();

        function sum(left,right){

            document.write(left + right + '<br>');

        }

        function sumColorRed(left, right) {

            document.write('<div style ="color=red;">' + left + right + '<div><br>');

        }

        sum(2,3); // 5

        sum(3,4); // 7

        sumColorRed(2,3); // 5

    </script>

     

    결과값이 23으로 출력. 두 값을 더하는 작업이 다양한 곳에서 사용된다면 이것은 필요에 따라 상당히 많은 함수를 만들어야 한다는 것을 의미. 이럴 때 return이 필요

     

     

    2. sum2() 함수 추가

    <h2>return</h2>

    <script>

        function sum2(left,right) {

    }

    </script>

     

    그런 다음 sum2(2,3) 을 숫자 5에 대한 표현식으로 만들고 싶음. 그리고 그 결과를 출력한 뒤 줄바꿈을 한다거나 결과의 글자색을 빨간색으로 표현하고 싶고, 경우에 따라 폰트의 크기를 다르게 하고 싶음.

     

     

    3. sum2() 함수 호출

     

    <script>

        function sum2(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>

     

    sum2(2,3)을 실행했을 때 sum()처럼 무엇인가를 알아서 실행하는 것이 아니라 sum2()를 실행한 결괏값을 돌려준다면?

     

     

    4. return 문 추가

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

     

     

     

    함수의 활용

     

    리팩터링: 동작하는 내용은 똑같지만 코드를 효율적으로 만드는 것.

    <input> 버튼의 자바스크립트 코드를 복사해서 <head>태그 안쪽에 <script>태그를 만들어 붙여넣고, 웹 브라우저에게 이러한 일련의 코드가 함수라는 것을 알림.

     

     

     

    1. nightdayhandler() 함수를 만들고 <input> 버튼의 자바스크립트 코드 넣기

        <script>

          function nightdayhandler() {

            var target= document.querySelector('body')

            if (this.value ==='야간 모드') {

              target.style.backgroundColor='#736D71';

              target.style.color='white';

              document.querySelector('h1').style.color='yellow';

              this.value='주간 모드'

     

              var alist = document.querySelectorAll('a');

              var i = 0;

              while (i < alist.length){

                  alist[i].style.color='#BEF3E8';

                  i = i + 1;

              }

            }

            else {

              target.style.backgroundColor='white';

              target.style.color='black';

              document.querySelector('h1').style.color='purple';

              this.value='야간 모드'

     

              var alist = document.querySelectorAll('a');

              var i = 0;

              while (i < alist.length){

                  alist[i].style.color='gray';

                  i = i + 1;

              }

            }

          }

        </script>

     

     

    2. onclick 속성값으로 nightdayhandler() 지정

    <input type="button" value="야간 모드" onclick="nightdayhandler();">

     

    그런데 버튼을 클릭해도 변화가 안 생기고, 한번 더 클릭해야 변화가 생김. 그리고 또 다시 클릭해도 주간 모드와 야간 모드라는 레이블은 바뀌지 않음. onclick 이벤트 안에서 this는 이 이벤트가 소속된 태그를 가리키도록 약속돼 있음. 독립된 nightdayhandler() 안의 코드에서 this 라는 값은 더 이상 input 버튼이 아니고, 전역 객체를 갖게 됨. 그래서 함수 안에서 this 값이 input 버튼을 가리키도록 nightdayhandler()이 실행될 때 this 값을 줌.

    그리고 function nightDatHandler(self)로 코드를 바꿔서 this라는 인자를 self라는 매개변수로 받음.

     

     

    3. this 인자를 self 매개변수로 받기

    <script>

        function nightdathandler(self){}

    </script>

    ...

    <input type="button" value="야간 모드" onclick="nightdayhandler(this);">

     

     

    4. 함수에서 this를 self로 변경

    function nightdayhandler(self) {

            var target= document.querySelector('body')

            if (self.value ==='야간 모드') {

              target.style.backgroundColor='#736D71';

              target.style.color='white';

              document.querySelector('h1').style.color='yellow';

              self.value='주간 모드'

              var alist = document.querySelectorAll('a');

              var i = 0;

              while (i < alist.length){

                  alist[i].style.color='#BEF3E8';

                  i = i + 1;

              }

            }

            else {

              target.style.backgroundColor='white';

              target.style.color='black';

              document.querySelector('h1').style.color='purple';

              self.value='야간 모드'

     

              var alist = document.querySelectorAll('a');

              var i = 0;

              while (i < alist.length){

                  alist[i].style.color='gray';

                  i = i + 1;

              }

            }

          }

     

    www.evernote.com/l/Alf8lnng1_JJq7vdy70IayqCQyavlvOvH4k/

     

    함수

    함수 예고 함수: 코드가 많아지면 그 코드를 잘 정리정돈하기 위한 도구 함수 1. ex9.html 파일 작성

    function

    basic

     

    www.evernote.com

     

Designed by Tistory.