독학

♧9/27 생활코딩 [자바스크립트] - 함수(좌우더하기, 출력=리턴 빨간색5, 밤낮토글리팩토링, 객체(나이트데이코드정리)

피자돈가스 2022. 9. 27. 23:15

<함수>

<불규칙적으로 반복되는 코드를 정리해보자>






이걸 함수로 만들거예요


 

이러면 컴퓨터는 two 라는 것을 함수로 만들고싶어하는구나 한다.




















-

결과

function sum(left, right){
        document.write(left+right+'<br>');

       }
       sum(2,3); /*5*/
       sum(3,4); /*7*/
 
이 자식의 기능:
1. 밑에 걸 좌항과 우항을 더한다
2. br태그를 추가해 줄바꿈을 해주고
3. 화면에 적어준다.
 
 
 







함수=입력과 (아규먼트 ) 출력(리턴)



만약 우리에게 함수와 , 출력값이 없었다면 이렇게 길게 코드를 짜야했을 것이다.









<출력코드를 통해 간단화하기>

과정




짠!

 

<script>
      function onePlusOne(){
        document.write(1+1+'<br>');
      }
      onePlusOne();
      function sum(left, right){
        document.write(left+right+'<br>');
      }
      function sumColorRed(left, right){
 
함수, 출력 사용하면 위와같은 거시기거시기.. 위에 계산하고 왼쪽 오른쪽에 써뒀던 걸 이거 여기에 좀 써줘라 ... 하는 구구절절한  코드가 아니라
위 사진처럼 간결하게 쓸 수 있는 것이다.
 
(1 = 그냥 5
 2 = 빨간 5
 3 = 빨갛고 큰 5)
 


페이지 모습은 이렇다. return부터 보면 된다. (중간에 5가 아니라 23 인건 선생님이 실수하셨다고 적혀있다.)






(함수 이론 끝~ 모든 코드와 결과 페이지)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>function</h1>
    <h2>basic</h2>
     <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>
    <h2>Parameter & Argument</h2>
    <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
      sumColorRed(2,3); // 5
      sum(3,4); // 7

    </script>
    <h2>return</h2>

    <script>
function sum2 (left, right){ 

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


    </script>
</body>
</html>














<함수를 이용해 나이트/데이 토글버튼을 효율적으로 바꿔보자. = 리팩토링>

바디태그에 있던 애들 스크립트 태그에 넣고, this 라고 돼있는 것들을 전부 self로 바꿔줘야한다. 그래야 내가 지정한 input을 가리킬 수 있게된다. (선생님이 지금은 이말 이해못한다면서 넘기라그러심.)



function nightDayHandler(self){

 
맨윗줄 요고는 새로 써준거다.
 
 
 




바디태그에

<body>

<input id="night_day" type="button" value="night" onclick="
nightDayHandler(this)
">
이거 있어야한다  this도 .
 
self 라는 매개변수로 this 를 바꾸는 것이다.
 


그러므로



이렇게 버튼이 전나 많아도 각자 알아서 잘 동작한다. 코드도 훨씬 줄고 가독성 좋고
스크립트 태그 속 나이트 데이라는 함수의 내용만 바꾸면 버튼들 다 바꾼대로 잘 작동하는 굿 코드인 것이다.






<객체 (오브젝트) 도구를 추가해보자.>


객체.. 정말 중요하지만 엄청 어렵다고 하신다. ㅜㅜ 큰 산중 하나가 함수고 그다음이 객체.
둘이 대립되는 개념이 아니라 함수 위에 객체가 있는 거다. 그래서 내용이 심화되는 느낌.


(딱 하나만 알려주겠다고하심. 객체가 이런거구나~ 하면서 들으라고 하심.)




-객체도 역시역시나 정리정돈을 위한 도구이다.
-함수와 연관돼있는 변수들이 많아지면 똑같이 복잡해지고,
서로 연관된 함수와 변수를 같은 이름으로 그루핑하고 정리정돈하기 위한 도구다.







시작


데이 나이트 토글 코드중 이거 중복되니까 객체로 정리해보자.





-

카피 후 마우스 커서 붙여넣어주고, powderblue 를 'color'; 로 바꿔준 후 ,

방금 복사 한 그 (밑의) 코드를 지울거임. 지우고 뭘 써넣었냐면 밑에 전체코드를 올리겠슴.







블루 저거도 바꾼거다.

<script>
function setColor(color){

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


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

          }
        }

</script>

</head>
<body>

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









그다음
<객체 또 추가되면 ?>

white 저놈에 대한 정리를 또 할라고 저놈 바로 위에 저렇게 추가했더니 어라라? 이전에 쓴 setColor 랑 이름이 겹쳐서 몽땅 덮어씌우게 될 위기다.
그럼 맨 위 이름 바꾸고 맨 아래에도 바꾼 이름 적어준 것과같이 하면됨. (사진은 말대로 바꾼 모습)

(화이트 저거 바꾼 모습) +추가로 블랙도 이름지어주고
두번째 코드 전 사진에 보면 그 코드는 타겟이 같아서 홈페이지가 이상해져서
저렇게 이름을 밑에서 복사해서 타겟부분만 바꿔준것임.












나머지는 다음시간에.. 디다뎌... 복습도 잘해야겠다 여기 확실이 자바스크립트 어렵다!