Article Taggé new Function
Dealing with Javascript variable scope and for-loop or external function.
Sometimes, you need to set some HTML attributes automatically with a batch declaration.
By example imagine you want to set an mouseover over hundred of <a> links, in order to display their title content in an alert box. How to proceed ?
You could try to achieve this using a loop. Something like:
<html>
<a id="0" href="./0" title="the first"> link number 0 </a>
<a id="1" href="./1" title="the second"> link number 1 </a>
<a id="2" href="./2" title="the third"> link number 2 </a>
<a id="3" href="./3" title="the fourth"> link number 3 </a>
<a id="4" href="./4" title="the fifth"> link number 4 </a>
</html>
<script>
var number_of_link = 5;
for(i=0;i<number_of_link;i++){
document.getElementById(i).onmouseover =
function(){
alert("I'm the number "+i+" link")
};
}
</script>
Just try this tiny snippet: have you seen the problem ?
Every link has a function showing the last value of the i variable!
So, what does happened ?
We start iterating over a integer called i. This variable is in a global socpe. For each element found, we set a new function, wich display the i value. But the variable is passed by raference, and we want it to be passed by value !
Fortunately, we have a solution: we will dynamically add a new Function object, which will result in “statically” defined function.
<html>
<a id="0" href="./0" title="the first"> link number 0 </a>
<a id="1" href="./1" title="the second"> link number 1 </a>
<a id="2" href="./2" title="the third"> link number 2 </a>
<a id="3" href="./3" title="the fourth"> link number 3 </a>
<a id="4" href="./4" title="the fifth"> link number 4 </a>
</html>
<script>
var number_of_link = 5;
for(i=0;i<number_of_link;i++){
document.getElementById(i).onmouseover =
new Function("alert("I'm the number "+i+" link)");
}
</script>
The Function constructor allow us to take a String, and declaring it as a function. This tip forces the js interpetor to build the string, and only after, to build the function itself. So we achieve to have a static number written in each function we defined and desired omouseover effect.
For further information about function creation, i should recommend you this page:
www.howtocreate.co.uk/tutorials/javascript/functions
Have a look too, to some article describing the javascript closure:
7 comments août 26, 2008