05.04 학습(개인)

한강섭·2025년 5월 4일
0

학습 & 숙제

목록 보기
80/103
post-thumbnail

JavaScript


동작원리

자바스크립트가 어디서 실행되는가?
바로 브라우저가 실행해준다 (크롬, 익스플로러 등등)
근데 뭔가 이상하게 동작한다 그걸 파악해보자

만약 1+1을 출력하고 setTimeout(1초, 2+2 출력) 하고 3+3을 출력하는 코드가 있다고 생각해보자

console.log(1+1)
setTimeout(function(){console.log(2+2)}, 1000)
console.log(3+3)

우리가 평소 사용하는 파이썬과 같은 언어는 2출력, 1초기다리고 4 출력, 다음에 6출력 으로 예상이된다. 하지만 결과는

2
6
4 (1초 후)

이렇게 출력된다 왜 그럴까?

동작과정 (gpt 설명)

  1. 코드가 실행되면 Global Execution Context가 생성되고 스택에 푸시됨
  2. 함수 호출 시 해당 함수의 Execution Context가 스택에 푸시됨
  3. 비동기 함수(setTimeout, fetch 등)는 Web API(브라우저) 또는 Node API(Node.js)로 전달됨
  4. 비동기 작업이 완료되면 콜백 함수가 태스크 큐에 추가됨
  5. 이벤트 루프는 스택이 비었을 때 태스크 큐에서 첫 번째 콜백을 스택으로 이동시켜 실행
  6. 이 과정이 계속 반복됨

쉬운 설명

비동기 처리가 필요한 함수들을 대기실에 넣어놓고 stack이 비었을 때 올려서 처리한다!
그러니깐 javascript에서 동기적으로 반복문 1000개 돌리고 이러면
버튼을 누르거나(이벤트리스너), ajax요청 후 코드 실행, setTimeout 타이머 같은 비동기 처리 함수들 다 대기실에서 손빨고 있어야 함..

  1. 스택을 절대 바쁘게 하지말자
  2. 큐를 절대 바쁘게 하지말자

javascript 기초


HTML 조작

javascript 는 HTML을 조작하기 위한 언어이다

document.getElementById('hello').innerHTML = '안녕';

document(HTML) 에서 hello라는 id를 (HTML 요소) 의 내부글자를 안녕으로 바꿔줘

이게 끝이다 이 방식을 활용해서 HTML을 조작해주면 된다!


UI 만들기

  1. 미리 디자인 해놓고 숨김 (css 적용)
display : none; // 숨기기
  1. 버튼 누르거나 하면 보여줌
<button onclick="document.getElementById('hello').style.display = 'block'"> 버튼 </button>

이런 방식으로 모든 UI 만들면 됨!


함수

위에 버튼이 불편하지는 않았는가?

개발자라면 당연히 불편해야 하고 이를 해결하기 위한 function을 만들어서 사용해야 한다!

<body>
  <div class="alert-box" id="alert">
    <p>Alert 박스</p> 
    <button onclick="shutDown()">닫기</button>
  </div>
  <button onclick="openUp()">버튼</button>
  <script>
    function shutDown(){
    document.getElementById('alert').style.display = 'none';
    }
    function openUp(){
    document.getElementById('alert').style.display = 'block';
    }
  </script>
</body>

shotDown과 openUP 함수를 통해 유지보수가 편해졌다!


함수 upgrade (파라미터)

혹시 위에 함수 두개가 너무 비슷해 보이지 않는가..?

개발자라면 불편해야하는데 이를 해결하기 위해 파라미터를 받는 함수를 통해 해결해보자!

<body>
  <div class="alert-box" id="alert">
    <p>Alert 박스</p> 
    <button onclick="alert('none')">닫기</button>
  </div>
  <button onclick="alert('block')">버튼</button>
  <script>
    function alert(command){
    document.getElementById('alert').style.display = command;
    }
  </script>
</body>

command 파라미터를 받아서 alert 함수 하나를 통해 조작 하였다


이벤트 리스너

여기서 html이 너무 더러워지고 있다는 생각이 들지는 않았나?

button 옆에 onclick 넣고 'none' 넣고 너무 복잡하고 html이 더러워진다..
onclick을 안쓰고 개발해보자!

  1. button에 id 붙이기
  2. script 에서 id 찾고 .addEventListener 동작!
<body>
    <div class="alert-box" id="alert">
      <p>Alert 박스</p> 
      <button id="close">닫기</button>
    </div>
    <button onclick="alert('block')">버튼</button>
    <script>
      
      function alert(command){
      document.getElementById('alert').style.display = command;
      }
      
      document.getElementById('close').addEventListener('click',function(){
        document.getElementById('alert').style.display = 'none';
      });
    </script>
  </body>

JQuery (라이브러리)

근데 요즘 JQuery 안쓴다던데..
왜냐하면 React가 HTML 조작을 약간 더 잘해서 그런데 JQuery로 개발된 사이트 1조1억개임 걍 공부 ㄱㄱ

<!DOCTYPE html>
<html>
  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <head>
    <meta charset="UTF-8">
    <title>Document</title>
    <link rel = "stylesheet" href="main.css">
  </head> 
  <body>
    <h4 id="test" class="test1">안녕하세요</h4>
    <script>
      
      document.getElementById('test').innerHTML = '안녕 javascript';
      document.querySelector('#test') // 쌩 자바스크립트 에서 query 쓰는 법 
      document.querySelectorAll('#test')[0] // 여러개 받고 싶을 때
      $('#test').html('안녕 jquery') // = getElementById 
      $('.test1').text('안녕 text') // = getElementsByClassName
      $('#test').css('color','red') // css 고치기 
      $('#test').attr('src','aaaa.jpg') // src, href 등등 달아주기 
    
    </script>
  </body>
</html>

간단하게 javascript 맛보기는 여기까지


TypeScript 맛보기

왜 나온거지?

JavaScript 는 5 - '3' 이 가능하다;; (Dynamic Typing)

이렇게 된다면 코드가 좀만 커진다면 쓰레기가 된다..

TypeScript에서는 오류로 검출해줌!
+오류 검출 메세지가 겁나 친절!

사실 JavaScript랑 문법이 거의 똑같기 때문에 코드 에디터 부가기능 역할로 봐도 된다

설치 방법

terminal 에서

npm install -g typescript

실행

.ts 파일 생성

tsconfig.json 생성 후 내용 작성

{
  "compilerOptions": {
    "target": "ES5",
    "module": "CommonJS",
  }
}

터미널 켜서 tsc -w 입력해두면 index.js 에 자동변환됨

문법 간단 요약

:string 이제 문자만 들어올 수 있다 (간단한 변수 타입지정)
string, number, boolean, null, undefined, bigint, [], {} 등

function 함수(x:number) :number{ //함수에도 지정 가능 
  return x*2
}

type Member = [number, boolean]; // 튜플 자료형 
let john:Member = [123, true];

class User{  // 클래스 
  name : string;
  constructor(name :string){
    this.name = name;
  }
}

참고자료

코딩애플 유튜브 강의

profile
기록하고 공유하는 개발자

0개의 댓글