MarksCode MarksCode - 1 year ago 84
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;

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 Source

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);

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download