How is this code snippet exercising closure?

Viewed 58

I was reading the chapter on Scope Closure, from getify's You don't know JS book series. I feel like I understand how closure works on the surface level at this point, but still can't figure out how this code snippet is exercising closure.

function setupBot(name,selector) {
    $( selector ).click( function activator(){
        console.log( "Activating: " + name );
    } );
}

setupBot( "Closure Bot 1", "#bot_1" );
setupBot( "Closure Bot 2", "#bot_2" );

How I see this is, upon calling the function the variables name and selector in the scope of setupbot are assigned the arguments and function activator is called upon click after which the function returns.

Which function has closure over which scope in this case?

2 Answers

The name variable is being saved in the closure created by

function activator(){
    console.log( "Activating: " + name );
}

So when you click on the corresponding selector, it logs that name.

The selector variable isn't referenced in the function, so it doesn't need to be saved in the closure. It's just used during the initial execution of setupBot().

A closure is created whenever a function contains a use of a variable declared outside the function, and the function is returned or saved somewhere (in this case, it's saved in the click event listener).

function setupBot(name, selector) {
  $(selector).click(function activator() {
    console.log("Activating: " + name);
  });
}

setupBot("Closure Bot 1", "#bot_1");
setupBot("Closure Bot 2", "#bot_2");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button id="bot_1">Bot 1</button>
<button id="bot_2">Bot 2</button>

The activator function is a new function which gets invoked when the selector element is clicked. So ideally it would not have had access to the name variable since it is not being defined in its scope. But because it is in a closure due to its outer function wrapper, it can access the name variable and hence this sample is an example of a closure.

Related