【问题标题】:lifetime of a variable inside a self invoking anonymous function - function closures自调用匿名函数内变量的生命周期 - 函数闭包
【发布时间】:2015-09-11 14:39:44
【问题描述】:

我正在研究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>

【问题讨论】:

    标签: javascript function


    【解决方案1】:

    在第一个示例中,counter 是一个全局变量,因为闭包中的 counter 超出了范围。其次,semih 不应该在函数内部,因为 innerHTML 需要一个字符串。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-07
      • 1970-01-01
      • 1970-01-01
      • 2013-02-23
      • 1970-01-01
      • 2015-12-08
      相关资源
      最近更新 更多