views:

62

answers:

2

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 linkElems 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.

+4  A: 
Pointy
+1  A: 

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