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.