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>
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP