JavaScript 中闭包和嵌套函数有什么区别?
JavaScript 闭包
在 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 嵌套函数
JavaScript 1.2 允许函数定义被嵌套在其他函数内。此外,还存在这样的限制,即函数定义不能出现在循环或条件中。这些对函数定义的限制,仅适用于带有 function 语句的函数声明。
示例
你可以尝试运行以下示例以了解如何实施嵌套函数
<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>
广告
数据结构
网络技术
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
python
C 编程语言
C++
C#
MongoDB
MySQL
JavaScript
PHP