0

the html and javascript is below:

<script>
    function a(k)
    {
        var i=0;

        if(k==0)
        {
            function b()
            {
                alert(++i);
            }
            return b;
        }
        else
        {
            function c()
            {
                alert(++i);
            }
            return c;
        }
    }

    var d=a(0);

    var e=a(1);

</script>

    <button onclick="d()">clickme</button>
    <button onclick="e()">clickme2</button>

the html and javascript is above.

I click the button "clickeme" first, the browser alert"1"; then I click the button "clickme2",the browser alert "1" too.

why?

after I click the button "clickme",the variable "i" have changed to 1;then,when I click the button "clickme2" the browser should alert "2". why?

the local function of b() and c() has it's own copy of variable "i"?

Alexis
  • 5,681
  • 1
  • 27
  • 44
pies
  • 61
  • 1
  • 1
  • 5
  • *"the local function has his own copy of outter variable in javascript closure?"* Each call to `a` creates a new `i` variable. The functions created within `a` *close over* that variable. So yes, each function returned by `a` has its own copy. See the linked question's answers for more details. – T.J. Crowder Jan 04 '18 at 08:18

1 Answers1

0

The issue is that your variable is defined and initialized within the a() function.

The code should be changed to this:

<script>
var i=0;

function a(k)
{


    if(k==0)
    {
        function b()
        {
            alert(++i);
        }
        return b;
    }
    else
    {
        function c()
        {
            alert(++i);
        }
        return c;
    }
}

var d=a(0);

var e=a(1);

Nimrod P.
  • 150
  • 5