The following js code, why do both counter and counter2 have a private scope I?

//  `i`

  function makeCounter() {
    // `i`  `makeCounter`.
    var i = 0;

    return function() {
      console.log( PPi );
    };
  }

  //  `counter`  `counter2`  `i`.

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

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

  i; // ReferenceError: i  ( makeCounter )
Jul.22,2021

counter = counter2 you get false , they are basically two different functions, but the behavior is the same.

despite the return statement, makeCounter () generates a local variable I every time it runs, so the I that runs multiple times is not the same variable. Local variables, this is easy to understand, right?

similarly, each time return is followed by function is also locally referenced, and each call to makeCounter () produces a different function expression object. Since each generated function is in the same scope as the corresponding I , this function can access the corresponding I .

The result of

return is to return the reference to the function expression, which is stored by counter and counter2 respectively, so counter and counter2 point to the same function expression object, and they use different I .


makeCounter()==makeCounter() //false

var a = makeCounter(); 
a() //  return `function`ai+1i=1;`a()`
 makeCounter() //

every time you execute makeCounter () , it is a new and same method, but the variable scope is also new, and you can no longer access it.

for example:

    var obj = {};
    var obj1 = {};
    var obj2 = obj;
    
    obj == obj1 //false
    obj == obj2 //true

does not seem to be the case. It should be that the variable I is reassigned every time the makeCounter method is called


New I, new function

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b3b2d0-2c279.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b3b2d0-2c279.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?