Wicked reference by parameter
There was an interesting JavaScript phenomenon while I was working with my team on a requirement. I mean it was more to do with the peculiar behavior when dynamically creating a Javascript function. Download the file event_test.txt and rename the file to event_test.html and open it in a browser.
The HTML will display a table with 1 row and 3 columns. The eventTest JavaScript function gets called when the page loads which binds a mouse over event showCounterNumber on every cell passing in the cell id which is also the cell number. On mouse over the cell number has to be displayed. You will notice that the alert always displays “3″ which is the value of the variable i after the loop completes in the eventTest method. You might have expected the value getting passed here, but looks like the variable reference is taken here. So if I wanted to have this page work the way we expect to work, the eventTest had to be changed to something like below.
function eventTest()
{
document.getElementById(0).onmouseover = function (){showCounterNumber(0)}
document.getElementById(1).onmouseover = function (){showCounterNumber(1)}
document.getElementById(2).onmouseover = function (){showCounterNumber(2)}
}
This would work as the value is directly hard coded rather than passing it through a variable. But in the actual requirement that we have, since the number of cells and which cell has to be bound to a mouse over event is dependent on lot of criteria and gets framed from the application on the server, what is the solution to this problem? The answer lies in the question itself, the eventTest method itself had to be created on the application running on the server and sent to the browser. By that way when the JavaScript reaches the browser it is something of the above form. Mysteriously the question remains in my mind why the integer value to the showCounterNumber has to be pass by reference when we have known the primitive types are passed by value?










