TIL. 12 JavaScript - ํ•จ์ˆ˜

Minjae Choiยท2021๋…„ 5์›” 20์ผ
0

JavaScript

๋ชฉ๋ก ๋ณด๊ธฐ
4/20

๐ŸŽˆ ํ•จ์ˆ˜๋ž€?

  • function(ํ•จ์ˆ˜) ํ”„๋กœ๊ทธ๋ž˜๋ฐ์—์„œ ํ•˜๋‚˜์˜ ํŠน๋ณ„ํ•œ ๋ชฉ์ ์˜ ์ž‘์—…์„ ์ˆ˜ํ–‰ํ•˜๊ธฐ ์œ„ํ•ด ๋…๋ฆฝ์ ์œผ๋กœ ์„ค๊ณ„๋œ ํ”„๋กœ๊ทธ๋žจ ์ฝ”๋“œ์˜ ์ง‘ํ•ฉ์ด๋‹ค.(๋ฆฌํŒฉํ† ๋ง์—์„œ ์•„์ฃผ ์ค‘์š”ํ•œ ์—ญํ• ์„ ์ฐจ์ง€ํ•œ๋‹ค.)
   <script>function nightDayHandler(){}</script>
   
   // nightDayHandler๋ผ๋Š” ํ•จ์ˆ˜ ์„ ์–ธ์ด๋ฉฐ, {}์•ˆ์—๋Š” JavaScript๊ฐ€ ๋“ค์–ด๊ฐ„๋‹ค.
  • argument(์ธ์ž) ์–ด๋–ค ํ•จ์ˆ˜๋ฅผ ํ˜ธ์ถœ์‹œ์— ์ „๋‹ฌํ•˜๋Š” ๊ฐ’์ด๋‹ค.
  • parameter(๋งค๊ฐœ๋ณ€์ˆ˜) ์ „๋‹ฌ๋œ ์ธ์ž๋ฅผ ๋ฐ›์•„๋“ค์ด๋Š” ๋ณ€์ˆ˜์ด๋‹ค.
   <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>
   
   // ํ•จ์ˆ˜๋กœ ์ „๋‹ฌํ•˜๋Š” 2, 3์ด๋ผ๋Š” ๊ฐ’์„ argument๋ผ๊ณ  ํ•˜๋ฉฐ,
   // ๊ฐ’์„ ๋ฐ›์•„์„œ ํ•จ์ˆ˜ ์•ˆ์œผ๋กœ ๋งค๊ฐœํ•ด์ฃผ๋Š” left, right๋ฅผ parameter๋ผ๊ณ  ํ•œ๋‹ค.
  • return ๊ฐ’์„ ๋ฐ˜ํ™˜ํ•˜๋Š” ๋ช…๋ น์–ด์ด๋ฉฐ, ๋ฆฌํ„ด์„ ๋งŒ๋‚œ ํ•จ์ˆ˜๋Š” ๊ฐ’์„ ์ถœ๋ ฅํ•˜๊ณ  ๋๋‚œ๋‹ค. ํ•จ์ˆ˜์˜ ๊ฐ€์žฅ ๋งˆ์ง€๋ง‰์— ๋“ค์–ด๊ฐ€์•ผ ํ•œ๋‹ค.

๐Ÿ“‹ ์‹ค์Šต

<head>
    <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>
</head>
<body>
    <h1><a href="index.html">WEB</a></h1>
    <input type="button" value="night" onclick="
        nightDayHandler(this)
    ">
    <input type="button" value="night" onclick="
        nightDayHandler(this)
    "> 
</body>
  • nightDayHandler๋ผ๋Š” ํ•จ์ˆ˜ ์„ ์–ธ ํ›„, ๋‚ฎ๊ณผ ๋ฐค์ด ๋ฐ”๋€Œ๋Š” ์ฝ”๋“œ๋ฅผ ์งœ๊ณ  onclick์— ๊ธด ์ฝ”๋“œ ๋Œ€์‹  nightDayHandler๋ผ๋Š” ํ•จ์ˆ˜๋ฅผ ๋„ฃ์–ด ๋ฆฌํŒฉํ† ๋งํ•œ๋‹ค.
  • ๊ธฐ์กด์— ์žˆ๋˜ this๋Š” ํ•จ์ˆ˜๋กœ ๊ฐ€๋ฉด์„œ self๋ผ๋Š” ๋งค๊ฐœ๋ณ€์ˆ˜๋ฅผ ์ •์˜ํ•˜๊ณ  ํ•จ์ˆ˜์—๋Š” nightDayHandler(self), onclick์—๋Š” nightDayHandler(this)๋กœ ์ž…๋ ฅํ•œ๋‹ค.
  • ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•จ์œผ๋กœ์จ ๋ช‡๊ฐœ์˜ ๋ฒ„ํŠผ์ด ๋˜์—ˆ๋“  ๊ฐ™์€ ์ด๋ฒคํŠธ ํšจ๊ณผ์˜ ๋ฒ„ํŠผ์„ ์‰ฝ๊ฒŒ ์ƒ์„ฑํ•  ์ˆ˜ ์žˆ๋‹ค.

โœ” ๊ฒฐ๊ณผ๋ฌผ

WEB

  1. HTML
  2. CSS
  3. JavaScript

0๊ฐœ์˜ ๋Œ“๊ธ€