익명 함수는 다른 라이브러리 코드와 충돌하지 않도록 가시성과 네임스페이스를 제어하기 위해 코드 조각, JavaScript 라이브러리, 함수 등을 래핑하는 데 사용됩니다. 이를 위해 IIFE(Immediately Invoked Function Expressions)가 사용됩니다.
다음은 JavaScript에서 Anonymous Wrapper Functions를 구현하는 코드입니다 -
예시
<!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;
color: blueviolet;
}
</style>
</head>
<body>
<h1>Anonymous wrapper functions in JavaScript</h1>
<div class="result">0</div>
<br />
<script>
let resEle = document.querySelector(".result");
(function () {
resEle.innerHTML =
"This piece of code is automatically executed as it is inside an IIFE";
})();
</script>
</body>
</html> 출력
