Is there a closure in this immediate execution function?

question:

  • is there a closure in this code?
  • Does
  • refer to variables outside the function as closures?

Code:

for (var i = 0; i < btns.length; iPP) {
  (function(j) {
    btns[j].onclick = function(i) {
      console.log("" + (i + 1) + "");
    };
  })(i);
}
Nov.25,2021

to understand closures, you need to understand the JS garbage collection (GC) mechanism. this article is more specific.

as far as the landlord's question is concerned, the answer is

  • has closures, and the implied assignment is var j = I
  • function A creates a variable, function A returns a function B, and function B refers to the variable created in function A, forming a closure (GC does not automatically collect)
Menu