본문 바로가기
Programming/Javascript

JS - 생활코딩

by DONGKU 2020. 6. 16.

출처: 생활코딩 JS


JS

사용자와 상호작용하는 언어

ctrl+d 다중선택


HTML과 JavaScript의 만남 1

<script>

웹브라우저는 <script> 안 쪽에 있 코드를 JS로 해석

    <script>
      document.write('hello world');
    </script>

 


HTML과 JavaScript의 만남 2

이벤트

구선생: javascript [ --- ] event attribute

onclick, onchange, onkeydown, etc..

  <body>
    <input type="button" value="hi" onclick="alert('hi')">
    <input type="text" onchange="alert('changed')">
    <input type="text" onkeydown="alert('key down!')">
// 동작시 on~ 이벤트 발생, alert은 경고창 띄움
  </body>

 


HTML과 JavaScript의 만남 3

Console

개발자도구에서 파일을 만들지 않고도 웹상에서 자바스크립트 코드를 즉석 사용 (필요한 데이터 처리)
보고있는 웹페이지를 대상으로도 JS 실행 가능

alert('문장'.length) // 글자수 알려줌

개발자도구 Elements 창에서 ESC를 누르면 html창과 함께 Console창 등장

console에서 실행 유보(줄바꿈): shift+Enter

 


데이터타입 - 문자열과 숫자

구선생: javascript string // 다양한 Method들 확인 가능 str.Method()

변수와 대입 연산자

변수를 사용할 때 var 붙여주자

 var name = 'dk';

 


제어할 태그 선택하기

구선생: javascript select tag by css selector
MDN webdocs

document.querySelector('body') // 이 문서(웹브라우저)에서 바디태그에게 질의한다

구선생: javascript element style, javascript style background-color

 


프로그램, 프로그래밍, 프로그래머

시간.순서

HTML은 시간의 순서대로 따르지 않으므로 프로그래밍 언어가 아니다
JS는 프로그래밍 언어

 


조건문의 활용

구선생: javascript element get value

조건문 Toggle

  <input id="night_day" type="button" value="night"onclick="          // id 값 설정
    if(document.querySelector('#night_day').value === 'night') {          // value값 비교
      document.querySelector('body').style.backgroundColor='black';
      document.querySelector('body').style.color='white';
      document.querySelector('#night_day').value = 'day';                     // Toggle을 위해 value값 바꿔줌
    } else {
      document.querySelector('body').style.backgroundColor='white';
      document.querySelector('body').style.color='black';
      document.querySelector('#night_day').value = 'night';
    }

 


리팩토링 중복의 제거

동작하는 것은 그대로두고 코드자체를 효율적으로 만들어 중복을 제거하고 가독성을 높이고 유지보수를 하기 편하게 만듦

중복을 끝까지 쫓아가서 다 없애 버려라

리팩토링 전

  <input id="night_day" type="button" value="night"onclick="          // id 값 설정
    if(document.querySelector('#night_day').value === 'night') {          // value값 비교
      document.querySelector('body').style.backgroundColor='black';
      document.querySelector('body').style.color='white';
      document.querySelector('#night_day').value = 'day';                     // Toggle을 위해 value값 바꿔줌
    } else {
      document.querySelector('body').style.backgroundColor='white';
      document.querySelector('body').style.color='black';
      document.querySelector('#night_day').value = 'night';
    }

리팩토링 후

  <input id="night_day" type="button" value="night"onclick="          
    if( this.value === 'night' ) {        // document.querySelector('#night_day') 는 자기 자신을 가리키므로 this 사용
      var target = document.querySelector('body');      // target 변수 선언
      target.style.backgroundColor='black';
      target.style.color='white';
      target.value = 'day';                    
    } else {
      target.style.backgroundColor='white';
      target.style.color='black';
      target.value = 'night';
    }

 


배열

구선생: javascript array
배열의 문법 미리 공부말고 필요할 때 찾아 쓰자

<script>
var dk = ["im", "dk"];
document.write(dk[0]);
</script>

 


반복문

구선생: javascript get element by css selector multiple

var alist = document.querySelectorAll('a');     // 모든 a 태그 불러옴
var i = 0;
while(i < alist.length){
     console.log(alist[i]);                                    // 출력
     alist[i].style.color = 'powderblue';              // a 태그들 색상 변경
     i=i+1;
}

 


함수

코드가 많아지면 정리정돈하는 도구

중복의 제거, 유지보수가 극단적으로 좋아짐

 

<script>function nightDayHandler(self){ // 독립된 함수를 만들게 되면 this는 소속된 태그가 없어지므로 매개변수로 받아서 사용 ~ }</script>

\`\`\` --- # 함수 # 연속적이지않게 반복된다면 반복문을 사용할 수 없다 => 함수 사용 # \`\`\`

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

\`\`\` # 리턴 # \`\`\`

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

## 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>'); // div 태그를 write안에 쓸 수 있음 document.write('<div style="font-size:3rem;">'+sum2(2,3)+'</div>'); // rem은 굉장히 큰 글자 단위</script>

\`\`\` # 리팩토링의 중요한 수단중의 하나가 함수 # --- # 객체 ### 함수라는 기반 위에 객체가 존재 ###객체: 함수와 변수가 많아지면 정리정돈하는 도구 ###서로 연관된 함수와 서로 연관된 변수를 같은 이름으로 그룹핑

 


객체 쓰기와 읽기

이름이 있는 정리 정돈 상자

배열은 [] 대괄호
객체는 {} 중괄호
coworkers.programmer
. 은 object access operator(객체에 접근 가능케 해주는 연산자)

    <script>
      var coworkers = {
        "programmer":"egoing",
        "designer":"leezche"
      };
      document.write("programmer : "+coworkers.programmer+"<br>");
      document.write("designer : "+coworkers.designer+"<br>");
      coworkers.bookkeeper = "duru";
      document.write("bookkeeper : "+coworkers.bookkeeper+"<br>");
      coworkers["data scientist"] = "taeho";
// 변수명에 띄어쓰기가 있을 때는 대괄호와 쌍따옴표 사용
      document.write("data scientist : "+coworkers["data scientist"]+"<br>");
    </script>

 


객체와 반복문

구선생: javascript object iterate

for(var key in coworkers) {    // coworkers 객체의 키 값들(programmer, designer, 배열에선 요소(index))을 하나하나 세팅 해줌
document.write(key+'<br>');   // key값들 불러옴
document.write(coworkers[key]+'<br>');  // 키값의 데이터 불러옴
}

 


객체 프로퍼티와 메소드

객체 소속된 변수의 값으로(프로퍼티) 함수를 지정할 수 있고, 객체에 소속된 함수를 만들 수 있다.(메소드)

      <script>
        coworkers.showAll = function(){    // 모든 각각의 데이터들을 iterate해서 화면에 출력
          for(var key in this){   
// 객체의 이름이 바뀌면 불러오지 못하므로, coworkers 대신 showAll 함수가 소속된 객체를 가리키는 약속된 기호 this 사용
            document.write(key+' : '+this[key]+'<br>');
          }
        }
        coworkers.showAll();
      </script>

 


객체 활용

    var Body = {
      setColor:function (color){
        document.querySelector('body').style.color = color;
      },     // 객체의 프로퍼티와 프로퍼티를 구분할 땐 ,(콤마) 사용
      SetBackgroundColor:function (color){
        document.querySelector('body').style.backgroundColor = color;
      }
    }

 


파일로 쪼개서 정리정돈 하기

가장 큰 정리 도구, 파일로 묶어서 그룹핑

역시나 웹페이지가 1억개라면.. 하나하나 다 바꿔야할까?
파일로 쪼갰을 때의 장점:
새로운 파일을 만들면 모든 코드를 카피할 필요 없이 심플하게 color.js 파일을 새로운 웹페이지에 포함시키면됨
작성했던 코드의 재사용! 모든 웹페이지에 동시에 변화가 반영!
유지보수 편리! 가독성! 이름을 통해 확인하는 코드의 명확성!
브라우저에 저장된 파일의 캐쉬를 통해 서버 입장에서 효율적!

 


라이브러리와 프레임워크

다른 사람의 도움을 받아 소프트웨어를 만든다, 다른 사람과 협력하는 모델이다

라이브러리: 내가 만들고 있는 프로그램에 사용할 부품을 가져온다.
프레임워크: 만들려고할 때 언제나 필요한 공통적인 것을 프레임워크가 만들어 놓고 달라지는 부분은 우리가 추가한다.(반제품)

jQuery 라이브러리

jQuery를 이용하면 반복문을 사용할 필요x

    // var alist = document.querySelectorAll('a');
    // var i = 0;
    // while(i < alist.length){
    //   alist[i].style.color = color;
    //   i = i + 1;
    // }
    $('a').css('color',color);    
// $는 jquery 표시, 웹페이지의 모든 a태그를 jquery로 제어, css함수로 속성 변경

수많은 JS 라이브러리 쏟아지고 있다. 새로운 것을 많이 알수록 Good!

UI vs API


API: 애플리케이션을 만들기 위해서 프로그래밍을 할 때 사용하는 조작 장치
애플리케이션은 API 들을 순서대로(프로그래밍적) 응용

 


수업을 마치며

프로젝트 시 모든 개념을 총동원하는 것이 아닌 필수불가결한 최소한의 도구만을 가지고 문제 해결

document.
웹페이지에 있는 어떤 태그를 삭제하고 싶거나, 어떤 태그에 자식 태그를 추가하고 싶다면 document 객체를 자세히 살펴보자
필요한 Method가 있을 것


DOM
document 객체로도 찾을 수 없다면 DOM(Document Object Model)으로 수색 범위를 넓혀보자
document 객체는 DOM객체의 일부

 

window
웹페이지가 아닌 웹브라우저 자체를 제어해야(열려있는 페이지 주소, 새창, 화면 크기) 한다면 window 객체를 살펴보자

 

ajax
웹페이지를 리로드하지 않고 정보를 변경하고 싶다면 ajax

 

cookie
웹페이지가 리로드되어도 현재 상태 유지
사용자를 위한 개인화된 서비스 제공

 

offline web application
인터넷이 끊겨도 동작하는 웹 페이지

 

webRTC
화상 통신 웹 앱

 

speech
사용자의 음성을 인식하고 음성으로 정보 전달

 

webGL
3차원 그래픽 게임

 

webVR
가상 현실

댓글