0
    function outer(a, b) {
        a.addEventListener('click', function inner(ev) {
            console.log(ev);
        });
    }

Will the event listener function in the example above still keep a reference to the [[scope]] of the outer function and cause a closure, even though the inner function doesn't explicitly mention any variables from the outside?

Will the context holding variables 'a' and 'b' still be kept in memory as long as the event listener function exists?

1 Answers1

0

Theoretically the outer variables should be retained if any of its inner functions are still reachable.
However, modern browsers (Chrome and FF, at least) will look inside them and determine if the outer variables themselves will actually be used or not, if not, they will be garbage collected.
To test it:
Copy & paste following code and run in browser console.
Then run console.log(a) and console.log(b) in console to see the difference, when it pauses.

function outer(a, b) {
  setTimeout(function inner() {
    debugger;
    a = 0;
  }, 1000);
}

var testA = 1
var testB = 1
outer(testA, testB);
Shanyu
  • 56
  • 3