The relationship between this and closure is a little confusing, who will show me?

the relationship between javascript this and closures is a little confusing. Which god comes in to have a look

recently, I was looking at the basic knowledge points related to js. I found a problem when I saw closures and this. Which god helped me analyze it? I analyzed it, and I couldn"t go on. The first one I searched the information on the Internet, and it seemed to explain clearly, but when I saw the second one, I found that it was impassable again. I know PPi and iPP, but the function context is confused again.

question 1

var i = 100;
function foo() {
    var i = 1;
    return function() {
        console.log(this.iPP);
    }
}
 
var f1 = foo(),f2 = foo();
foo()(); //100
f1(); //101
f1(); //102
f2(); //103
Apr.11,2021

question 1: this points to the object that called it. Object.getNameFunc () () because object.getNameFunc () returns a method, let's say fun2, equals fun2 (), equals window.fun2 (), so this points to window. Similarly, object.getName () this points to object.
question 2:
the first piece of code f1f2 foo () is independent at first, and when it is executed, it forms its own closure without receiving influence, which is the I in its respective scope, so F1 executes its corresponding I plus several times, which has nothing to do with the I of f2.
the second section of the code refers to question 1, this points to window, and the global I is window.i, so the I in F1 () f2 () f () () is actually the same, that is, window.i


in the first section of the code, all the I points to the I defined in foo, where the I of f1/f2/foo () () is independent;

the second piece of code, this always points to window, so the whole process is operating on the same I, that is, globally defined I, with an initial value of 100

.

the first code is the understanding of closures
1.f1=foo (). F2=foo (), foo execution environment initialization. The I of the execution variables corresponding to two different execution environments is undefined;
1.foo () (). Execute this function directly and get the value 1 of I in the execution environment generated by the current function.
2.f1 (): creates F1 () to create the execution environment of F1 (). Initially, the I in the current active object is 1, and the global scope is less than 100 at the lower level of the scope chain of the foo function;
3.f1 (): F1 () creates the execution environment again, and the function execution environment at this time variable I, at this time I is 2.
4.f2 (): creates f2 (), which produces the execution environment of f2 (), and I is 1 in the current active object.
two execution environments with different execution variables that do not interfere with each other

When the

second paragraph
executes the function, the function executes in the global environment and operates on the global scope I, so it accumulates

all the time.
Menu