try~catch
예외처리 프로세스 예상되는 에러를 try{code...} 영역에 배치를 하고, 만약 에러가 발생하면
catch(err){code...}영역에서 처리하는 예외처리 프로세스
- try영역 : 에러가 발생할 수 있는 코드를 실행 자바스크립트에서 에러가 발생하면 에러 발생 라인부터 동작이 멈춤. 에러가 발생해도 다음코드로 넘어감.
- catch(err){ } : 에러가 발생하면 예외처리를 하는 곳.
- try~catch로 예외처리를 하면 프로세스가 멈추지 않고, 지속시킬 수 있음.
- finally영역 : 예외처리와 상관없이 무조건 실행되어야 하는 코드를 넣는 영역
- throw : 예외를 고의적으로 발생시키는 키워드 throw + 예외발생 후 처리코드
ex)
<script>
console.log('프로세스 시작');
let num = 0;
let arr=[1,2,3]
try{
alert('경고창');
throw new '경고창 에러시 문구';
console.log(10+num);
console.log(10-num);
}catch(err){
console.log(err.name);
console.log(err.message);
}finally{
console.log("꼭 출력되어야 하는 문구");
}
</script>
클래스, 생성자, 객체
클래스 생성 기본 문법
- 클래스는 반드시 첫글자 대문자
class MyClass{
//생성자 : 자바스크립트의 생성자는 1개만 허용
constructor(param){
...
}
//method 정의
methodName(param){
....
}
methodName(param){
....
}
//getter/setter
get name(){
return this.name;
}
set name(value){
this.name = value;
}
}
ex) class User 생성
name, birth를 받아서 멤버변수로 저장하고
get age() 나이를 리턴
status() 성인인지 미성년자인지 리턴 (콘솔에 출력)
<script>
class User{
constructor(name, birth){
this.name = name;
this.birth = birth;
}
get age(){
let birthday = new Date(this.birth);
let todayYear = new Date().getFullYear();
return todayYear - birthday.getFullYear();
}
status(){
if(this.age < 20){
return '미성년자';
}
return '성인';
}
}
let hong = new User('hong','2009-09-30');
console.log(hong.age);
console.log(hong.status());
let kim = new User('kim','1990-01-01');
console.log(kim.age);
console.log(kim.status());
</script>
생성자함수 : 클래스의 함수화
class, 생성자함수, 객체
일반 함수와 생성자 함수는 별반 차이가 없음.
1. 반드시 new 를 통해 실행
2. 반드시 함수 첫글자를 대문자로 시작.
ex) 클래스 함수 활용 구구단 문제 만들어보기
<body>
<!-- 구구단 문제 -->
<h1>
<button type="button" id="startBtn">문제출제</button>
</h1>
<ol id="q"></ol>
<h1>
<button type="button" id="compareBtn">정답확인</button>
</h1>
<h3 id="printRatio"></h3>
<script>
const ansObj = {}; //정답을 담을 객체
//ansObj[`ans${i}`] = dan * incre;
let quizArea = document.getElementById('q');
let count=0; //전체개수
let correct = 0; //정답개수
document.getElementById('compareBtn').addEventListener('click',()=>{
correct=0;
count=0;
while(count < 10){
count++;
let userInput = document.getElementById('userAns'+count);
if(userInput.value == ansObj[`ans${count}`]){
correct++;
userInput.value += " : 정답!!";
userInput.style.backgroundColor = 'green';
}else{
userInput.value += " : 오답!!";
userInput.style.backgroundColor = 'red';
}
}
document.getElementById('printRatio').innerText =
`정답갯수 : ${correct}, 정답률 : ${(correct/count).toFixed(2)*100}%`;
});
document.getElementById('startBtn').addEventListener('click',()=>{
count=0;
document.getElementById('printRatio').innerText = "";
let q = '';
do{
count++;
let dan = Math.floor(Math.random()*8)+2;
let incre = Math.floor(Math.random()*9)+1;
let answer = dan * incre;
ansObj[`ans${count}`] = answer; //object에 정답 추가
//값 뿌리기
q+= `<li>${dan} * ${incre} = <input type="text" id="userAns${count}"> </li>`;
}while(count < 10);
quizArea.innerHTML = q;
console.log(ansObj);
});
</script>
</body>
'화면 수업 정리' 카테고리의 다른 글
HTML,CSS,JS 15일차 (0) | 2024.08.14 |
---|---|
HTML,CSS,JS 14일차 (0) | 2024.08.13 |
HTML,CSS,JS 12일차 (0) | 2024.08.09 |
HTML,CSS,JS 11일차 (0) | 2024.08.08 |
HTML,CSS,JS 10일차 (0) | 2024.08.07 |