views:

63

answers:

2

Some time ago I posted a question about what questions should a good javascript coder be able to answer. Meder pointed out the following question:

The following code makes clicks on any "a" element to alert(-1) due to the fact that "i" is hold in the onclick function as a reference and not as a value:

<a href="#">text</a><br><a href="#">link</a>
<script>
var as = document.getElementsByTagName('a');
for ( var i = as.length; i--; ) {
    as[i].onclick = function() {
        alert(i);
        return false;
    }
}
</script>

The question is: How to fix this implementation so that the onclick function holds the value of i and not it's reference?

I don't know the answer. How to fix it? How to make i to be a copy of the reference value rather than the actual reference?

Side questions: Are all variable types passed in as a reference? Or does it vary on whether it's a primitity type or an object?

Any thoughts would be appreciated.

+1  A: 
<a href="#">text</a><br><a href="#">link</a>
<script>
var as = document.getElementsByTagName('a');
for ( var i = as.length; i--; ) {
    as[i].onclick = function() {
        return function() {
           alert(i);
           return false;
        }
    }();
}
</script>

maybe?

Shawn Simon
You are *almost* there... hint: you have to capture the `i` variable by passing it as an argument to the self-executing function...
CMS
+2  A: 

To understand this problem, you must learn what a closure is. Then you must also know how javascript deals with scope (it is on a function-basis rather than on a block-basis as C for example).

Here's the "stantard" solution:

<a href="#">text</a><br><a href="#">link</a>
<script type="text/javascript">
var as = document.getElementsByTagName('a');
for ( var i = as.length; i--; ) {
    as[i].onclick = (function(i) {
        return function() {
            alert(i);
            return false;
        }
    })(i);
}
</script>

Another version that does exactly the same thing, but might be easier to understand if you are not used to closures and scope in JS is:

for ( var i = as.length; i--; ) {
    as[i].onclick = (function(number) {
        return function() {
            alert(number);
            return false;
        }
    })(i);

Got the idea?

Bruno Reis
Got the idea! thanks!
Ciwee