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