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嵌套函数
JavaScript1.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>热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下