Yes, this is closing.
Each time a function is executed , a new object is created to store (as its properties) the variables declared with var and each function declared inside it. This object is called the execution context (or sometimes the scope object).
Each time a function is declared ( or defined in an expression), a new function binds to it an execution context object that is current. This creates a so-called chain of scope.
When executing the code, you must enable the identifier for the value that it first looks for in the properties of the current execution context. If the identifier is not found, it uses an output context object attached to the function being executed. It continues to climb the chain of visibility until it reaches a global level.
In your example, every time the โself-run functionโ is executed, a new execution context object is created that creates the el and num properties. Since the function assigned to onclick is created inside this execution context, each time you get a new instance of this function. These instances will have a corresponding execution context object. Therefore, the first will have an execution context when num was assigned 1, the second will have an execution context where num was assigned 2, etc.
When each of the onclick functions runs the code, it will first look for the identifier num in the current execution context. However, this internal function is not var num, so it is not found. Therefore, Javascript considers the execution context attached to the function when it was created. Here he will find num , num will contain the value assigned to him during this iteration, as described above.
source share