vendredi 11 septembre 2015

lifetime of a variable inside a self invoking anonymous function - function closures

I'm studying function closures from http://ift.tt/1vKs8WG

I don't understand the below code. variable add refers to a self-invoking anonymous function which returns an anonymous function. In this case, what happens to variable counter? when we call function add, what happens?

<!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>

in addition I dont understand why the code below does not work?

<!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>



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire