在本文中,我们将了解“闭包”以及它们在 javascript 中的实际工作原理。闭包基本上是一个函数的组合,该函数包含对其周围状态的引用(也称为词法环境)。
在 JavaScript 中,基本上每次在运行时创建函数时都会创建闭包。换句话说,闭包只是一个奇特的名称,它记住了内部使用的外部事物。
让我们通过一些示例来了解 JavaScript 闭包 -
在下面的示例中,我们将声明一个闭包,最终能够从外部函数访问外部变量 tagLine
在最内部函数中使用外部变量后,这个特定的闭包将帮助用户在每次调用外部函数时提醒 tagLine。
立即学习“Java免费学习笔记(深入)”;
#Filename: index.html
<!DOCTYPE html>
<html>
<head>
<title>
Closures in Javascript
</title>
</head>
<body>
<h1 style="color: green;">
Welcome To Tutorials Point
</h1>
<button type="button" onclick="init()">
Click here!!!
</button>
<p id="demo"></p>
<script>
function init() {
var tagLine = "Start your Learning journey now";
function display() { // display() is the inner function, a closure
alert(tagLine); // use variable declared in the parent function
}
display();
}
</script>
</body>
</html>这将产生以下结果。

在下面的示例中,我们使用嵌套闭包调用两个函数并显示同一函数的输出。
#文件名:index.html
<!DOCTYPE html>
<html>
<head>
<title>
Closures in Javascript
</title>
</head>
<body>
<h1 style="color: green;">
Welcome To Tutorials Point
</h1>
<button type="button" onclick=" Counter()">
Click Me!
</button>
<p id="demo1"></p>
<p id="demo2"></p>
<script>
function Counter() {
var counter = 0;
function outerfunction() {
counter += 1;
document.getElementById("demo1").innerHTML
= "Outer Counter called = " + counter +" from Outer Function " ;
function innerfunction() {
counter += 1;
document.getElementById("demo2").innerHTML
= "Inner Counter called = " + counter +" from Inner Function ";
};
innerfunction();
};
outerfunction();
};
</script>
</body>
</html>
以上就是JavaScript 中的闭包是如何工作的?的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号