我正在研究 http://www.w3schools.com/js/js_function_closures.asp 中的函数闭包
我不明白下面的代码。变量add指的是一个自调用的匿名函数,它返回一个匿名函数。在这种情况下,变量计数器会发生什么情况?当我们调用函数add时,会发生什么?
<!DOCTYPE html>
<html>
<body>
<p>Counting with a local variable.</p>
<button type="button" onclick="myFunction()">Count!</button>
<p id="demo">0</p>
<script>
var add = (function () {
var counter = 0; })();
return function () {return counter += 1;}
function myFunction(){
document.getElementById("demo").innerHTML = add();
}
</script>
</body>
</html>
另外我不明白为什么下面的代码不起作用?
<!DOCTYPE html>
<html>
<body>
<p>Counting with a local variable.</p>
<button type="button" onclick="myFunction()">Count!</button>
<p id="demo">0</p>
<script>
var add = (function () {
var counter = 0;
return function ()
{
var semih=0;
if(counter >5)
{
return function(){ semih += 5; }
}
return counter += 1;}
}
)();
function myFunction(){
document.getElementById("demo").innerHTML = add();
}
</script>
</body>
</html>
最佳答案
在第一个示例中,计数器是一个全局变量,因为闭包中的计数器超出了范围。在第二个中,semih 不应该位于函数内部,因为innerHTML 需要一个字符串。
关于javascript - 自调用匿名函数内变量的生命周期 - 函数闭包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32526076/