2강 — class, 비동기, DOM
2024 DTC
| → / Space | 다음으로 |
| ← | 이전으로 |
| ↓ / ↑ | 같은 주제 안에서 단계 이동 |
| O | 전체 슬라이드 한눈에 보기 |
| F | 전체화면 |
아래쪽 화살표가 보이면 그 주제는 단계별로 이어집니다
| const / let | 값에 이름 붙이기 |
| { } | 객체 — 이름으로 꺼낸다 |
| function / => | 묶어서 재사용하기 |
오늘은 여기서 이어집니다
비슷한 객체를 여러 개 만들려면
const rabbit = {
height: "100cm",
weight: "5kg"
};
const r1 = { height: "100cm", weight: "5kg" };
const r2 = { height: "80cm", weight: "4kg" };
const r3 = { height: "95cm", weight: "6kg" };
// ...
토끼가 백 마리면 어떻게 할까요?
class Rabbit {
constructor({ height, weight }) {
this.height = height;
this.weight = weight;
}
}
const rabbit = new Rabbit({
height: "100cm",
weight: "5kg"
});
const rabbit = new Rabbit({
height: "100cm",
weight: "5kg"
});
rabbit.height;
rabbit.height"100cm"
class Rabbit {
constructor({ height, weight }) {
this.height = height;
this.weight = weight;
}
jump() {
console.log("점프함");
}
}
const rabbit = new Rabbit({ height: "100cm" });
rabbit.jump();
class — 객체를 찍어내는 틀constructor — new로 만들 때 한 번 실행this — 지금 만들어지는 그 객체지금이 아니라 나중에 실행하려면
setTimeout(() => {
// 실행할 코드
}, ms);
setInterval(() => {
// 실행할 코드
}, ms);
setTimeout(() => {
console.log(1);
}, 1000);
console.log(2);
여기서 1과 2 중 뭐가 먼저 나올까요?
setTimeout(() => {
console.log(1);
}, 1000);
console.log(2);
setInterval(() => {
console.log(1);
}, 1000);
console.log(2);
const timer = setInterval(() => {
console.log(1);
}, 1000);
setTimeout(() => {
clearInterval(timer);
}, 5500);
한 번만 실행
clearTimeout으로 취소간격을 두고 계속
clearInterval로 정지언젠가 끝날 작업을 다루려면
서버에서 자료를 받아오는 데
1초가 걸린다면?
그동안 화면이 멈춰 있으면 안 된다
Promise가 가지는 세 가지 상태
const promise = new Promise((resolve, reject) => {
let success = true;
if (success) {
resolve("이행됨");
} else {
reject("거부됨");
}
});
promise
.then((message) => {
console.log(message);
})
.catch((message) => {
console.error(message);
});
// success = false 로 바꾸면
promise
.then((message) => {
console.log(message);
})
.catch((message) => {
console.error(message);
});
then — 성공했을 때catch — 실패했을 때Promise를 읽기 쉽게 쓰려면
fetch(url)
.then((response) => response.json())
.then((data) => {
console.log(data);
})
.catch((error) => {
console.error(error);
});
async function fetchData() {
try {
const response = await fetch(url);
const data = await response.json();
console.log(data);
} catch (error) {
console.error("Error:", error);
}
}
fetchData();
async 함수는 항상 Promise를 반환한다await는 Promise가 끝날 때까지 기다렸다 결과를 꺼낸다await는 async 함수 안에서만 쓸 수 있다
async function hello() {
return "안녕";
}
hello();
hello().then((v) => console.log(v));
hello()Promise { "안녕" }then 안의 v"안녕"이어 붙이는 방식
길어지면 읽기 어렵다위에서 아래로
try/catch로 오류 처리JavaScript로 화면을 바꾸려면
DOM
= Document Object Model
HTML 문서를
JavaScript가 다룰 수 있는 객체로 만든 것
그래서 document. 으로 시작한다
document.getElementById()
document.getElementsByTagName()
document.getElementsByClassName()
document.querySelector()
document.querySelectorAll()
// 대상 HTML
// <p>첫 번째</p>
// <p>두 번째</p>
let obj = document.getElementsByTagName("p");
obj[0];
obj[1];
obj[0]<p>첫 번째</p>obj[1]<p>두 번째</p>
// CSS 선택자를 그대로 쓴다
document.querySelector("#title");
document.querySelector(".msg");
document.querySelectorAll(".msg");
#titleh1 하나.msg첫 번째 p 하나querySelectorAllp 전부
const title = document.querySelector("#title");
title.textContent = "반갑습니다";
첫 번째 문단
두 번째 문단
const title = document.querySelector("#title");
title.style.color = "tomato";
title.style.fontSize = "3rem";
첫 번째 문단
두 번째 문단
const box = document.querySelector("#list");
box.innerHTML = "<p>새로 넣은 문단</p>";
새로 넣은 문단
| querySelector | CSS 선택자로 하나 찾기 |
| querySelectorAll | 조건에 맞는 것 전부 찾기 |
| textContent | 글자만 바꾸기 |
| innerHTML | HTML째로 바꾸기 |
| style.속성 | 스타일 바꾸기 (fontSize처럼) |
사용자의 동작에 반응하려면
지금까지는 코드를 내가 실행했습니다
이제는 사용자가 버튼을 눌렀을 때 실행되게 만듭니다
대상.addEventListener("이벤트이름", () => {
// 그때 실행할 코드
});
const btn = document.querySelector("#btn");
btn.addEventListener("click", () => {
console.log("눌렸다");
});
let count = 0;
const btn = document.querySelector("#btn");
const out = document.querySelector("#out");
btn.addEventListener("click", () => {
count++;
out.textContent = `${count}번 눌렀습니다`;
});
3번 눌렀습니다
| click | 클릭했을 때 |
| input | 입력창에 글자를 칠 때 |
| submit | 폼을 제출할 때 |
| keydown | 키를 눌렀을 때 |
| load | 페이지가 다 불러와졌을 때 |
addEventListener로 미리 등록해둔다오늘 배운 것
| class | 객체를 찍어내는 틀. constructor, this, 메서드 |
| setTimeout | 한 번 나중에 |
| setInterval | 간격을 두고 계속. clearInterval로 정지 |
| Promise | pending → fulfilled / rejected |
| then / catch | 성공 / 실패 처리 |
| async / await | 같은 일을 위아래로 읽히게 |
| querySelector | 화면에서 요소 찾기 |
| textContent / style | 찾은 요소 바꾸기 |
| addEventListener | 사용자 동작에 반응하기 |
직접 만들어봅시다
1강의 HTML/CSS 실습 페이지에 얹어보면 좋습니다
수고하셨습니다