자바스크립트 폐쇄
JavaScript에서 모든 함수는 클로저처럼 작동합니다. 클로저는 호출될 때 선언된 범위를 사용하는 함수입니다. 호출된 범위가 아닙니다.
다음은 예입니다.
라이브 데모
<!DOCTYPEhtml>
<html>
<body>
<h2>JavaScriptClosures</h2>
<script>
varp = 20;
functiona(){
var p = 40;
b(function(){
alert(p);
});
}
functionb(f){
var p = 60;
f();
}
a();
</script>
</body>
</html> 자바스크립트 중첩 함수
JavaScript 1.2에서는 함수 정의가 다른 함수 내에서도 중첩될 수 있습니다. 그러나 함수 정의가 루프 또는 조건부 내에 나타나지 않을 수 있다는 제한이 있습니다. 함수 정의에 대한 이러한 제한은 함수 문이 있는 함수 선언에만 적용됩니다.
예시
다음 예제를 실행하여 중첩 함수를 구현하는 방법을 배울 수 있습니다.
라이브 데모
<html>
<head>
<script>
<!--
functionhypotenuse(a,b) {
functionsquare(x){returnx*x;}
returnMath.sqrt(square(a)+square(b));
}
functionsecondFunction() {
varresult;
result=hypotenuse(5,4);
document.write(result );
}
//-->
</script>
</head>
<body>
<p>Clickthe following button to call the function</p>
<form>
<inputtype="button"onclick="secondFunction()"value="CallFunction">
</form>
<p>Usedifferent parameters inside the function and then try...</p>
</body>
</html>