MarksCode MarksCode - 3 months ago 14
Javascript Question

Do event listeners work like returned inner functions?

I'm getting familiar with closures in javascript thanks to this fantastic stackoverflow answer. I noticed that if I have the following code:

function main(){
var a = 5;
var b = 5;
inner();

function inner(){
$('#btn').on('click', function(){
alert(a + b);
});
}
}


Any time the button is clicked on 10 will be alerted. However, unlike the examples in that stackoverflow answer the inner function isn't returned.

Do event listeners like the one I gave in the example remember their scope just like returned inner functions of closures?

Answer

A closure doesn't have to be returned, any mechanism that gets a reference to it outside the containing function will save the environment with it. So instead of returning the function you could assign it to a global variable, e.g.

var fun;

function main() {
  var a = 5;
  var b = 5;
  fun = function() {
    alert(a + b);
  };
}
main();
fun();

An event listener is just a global data structure associated with the DOM element, and the closure works the same way with that.

Comments