简体   繁体   中英

How come a i variable is a “copy” and not a reference to the original i

I am bit confused by the following JavaScript code:

    // Because this function returns another function that has access to the
    // "private" var i, the returned function is, effectively, "privileged."

    function makeCounter() {
      // `i` is only accessible inside `makeCounter`.
      var i = 0;

      return function() {
        console.log( i++ );
      };
    }

    // Note that `counter` and `counter2` each have their own scoped `i`.

    var counter = makeCounter();
    counter(); // logs: 1
    counter(); // logs: 2

    var counter2 = makeCounter();
    counter2(); // logs: 1
    counter2(); // logs: 2

    i; // ReferenceError: i is not defined (it only exists inside makeCounter)

I don't understand how come the i variable in counter and counter2 aren't referring to the same i value?

My understanding is that counter and counter2 should reference the same function since both have been assigned the same function and a function is a "reference datatype" and shouldn't create a separate copy.

Also, how is it possible the counter and counter2 access the "private" value set in makecounter function?

i is local to makeCounter .

You get a new i each time that function is invoked .

The anonymous function defined inside that function has access to i because it is defined inside makeCounter .

That function is returned, so it is available outside makeCounter but it still has access to i because of where it was defined.

My understanding is that counter and counter2 should reference the same function since both have been assigned the same function

They haven't been assigned the same function. A new function was created each time makeCounter was invoked.

One thing you need to understand is that Javascript uses static scoping. So the variable i is only available in the scope of makeCounter function.

When you are calling makeCounter() it initializes i to 0 and returns a new function object. And for each function object has its own instance of i.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM