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