Question: Here's some JavaScript:

```
linkElem.click(function () {
    var data = linkElem.data();
    alert(''+data.mls + ' ' + data.id);
});

```

It works.

`linkElem` is a local variable that I create in a loop inside a function. I assign some data to it with jQuery's `.data()`. If I did not call `.click()`, `linkElem` would be reassigned during the loop and then recycled after the function returns. However, I have created an anonymous function which references `linkElem`. So I am no longer sure what is going on.

My guess is that all of the anonymous functions and `linkElem`s created during the loop are given UIDs of some kind and moved to persistent/global scope. Is this correct? Gratuitous detail would be much appreciated.

Answer: 
Yes, your description is pretty close. The local storage for a Javascript function call is just a block of memory allocated for local variables. If you "capture" that by creating *another* function *inside* a called function, then the storage is retained and the local variables carry on with their lives, unaware that the function that gave them birth might be long dead.

It's important to keep in mind that *only* functions create such storage — things like brace-enclosed loop bodies are *not* separate storage areas. Thus a common error is to declare a variable in a function and re-use it among several functions created in a loop. That's not inherently wrong, but the effect can be surprising:

```
function whatever() {
  for (var i = 0; i < 3; ++i) {
    setTimeout(function() { alert(i); }, 5000);
  }
}

```

If you run that, you'll see three alerts that all say "3". Why? Because they all *share* the same "i" variable. You can avoid that by introducing *another* function layer:

```
function whatever() {
  for (var i = 0; i < 3; ++i) {
    setTimeout((function(private_i) { return function() { alert(private_i); }; })(i), 5000);
  }
}

```

The "wrapper" function is just there to provide a local variable (the parameter "private\_i") whereto the loop variable "i" can be copied.
> 
> However, I have created an anonymous function which references linkElem. So I am no longer sure what is going on.
> 
> 
> 

It still gets reassigned, unless you are wrapping it in another level of scope (NB: another function).

Consider the following:

```
for (var j = 0;j < 10;j += 1) {
    arrayOfLinks[j].onclick = function () {
        alert(j);
    };
}

```

In this case, all of those links would alert `10` when clicked, because `j` is outside of the scope and is being updated.

If you're creating `linkElem` in the same way, you are likely to only get the result of the *last* `linkElem` in the loop.

This is a better way:

```
linkElem.click(function () {
    var data = $(this).data(); // no longer dependent on `linkElem` reference
    alert(''+data.mls + ' ' + data.id);
});

```