ES2019에 도입된 선택적 catch 바인딩을 사용하면 catch 바인딩의 주변 괄호를 제거할 수 있습니다. 즉, 오류 개체를 저장하기 위해 변수를 사용할 필요가 없습니다. 특히 오류에 대해 미리 알고 있거나 오류에 대해 알지 못한 채 대응하려는 경우에 유용합니다.
다음은 JavaScript의 선택적 catch 바인딩에 대한 코드입니다. -
예시
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.result {
font-size: 20px;
font-weight: 500;
}
</style>
</head>
<body>
<h1>Optional Catch Binding in JavaScript.</h1>
<div style="color: green;" class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to generate an error</h3>
<script>
let resEle = document.querySelector(".result");
document.querySelector(".Btn").addEventListener("click", () => {
try {
resEle.innerHTML = a;
}
catch {
resEle.innerHTML = "The variable a has not been declared";
}
});
</script>
</body>
</html> 출력
위의 코드는 다음과 같은 출력을 생성합니다 -

'여기를 클릭' 버튼을 클릭하면 -
