JavaScript 1.2에서는 함수 정의를 다른 함수 내에서도 중첩할 수 있습니다. 여전히 함수 정의가 루프나 조건문 내에 나타나지 않을 수 있다는 제한이 있습니다. 함수 정의에 대한 이러한 제한은 function 문이 있는 함수 선언에만 적용됩니다.
예시
다음 코드를 실행하여 JavaScript 중첩 함수를 구현하는 방법을 배울 수 있습니다. −
<html>
<head>
<script>
function hypotenuse(a, b) {
function square(x) { return x*x; }
return Math.sqrt(square(a) + square(b));
}
function secondFunction(){
var result;
result = hypotenuse(3,4);
document.write ( result );
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type = "button" onclick = "secondFunction()" value = "Find Hypotenuse">
</form>
</body>
</html>