Andre Pena
Andre Pena

Reputation: 59336

How to copy the value of a reference in javascript?

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.

Upvotes: 4

Views: 2019

Answers (2)

Bruno Reis
Bruno Reis

Reputation: 37822

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?

Upvotes: 3

Shawn
Shawn

Reputation: 19803

<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?

Upvotes: 1

Related Questions