[Javascript] global vars prob?!
Nick Fitzsimons
nick at nickfitz.co.uk
Fri Feb 10 13:18:02 CST 2006
Michael Borchers wrote:
> i dynamically create a textarea in a for() like this:
>
> var offersNumRows = 2
>
> var offersNumRowsAdded=4 (f.e.)
>
> for(o=0;o<offersNumRowsAdded;o++)
> {
>
> var numRow = offersNumRows + o;
<snip>
> HERE COMES THE TROUBLE MAKER:
> inputProductsDescription.onfocus=function() {
> products_price_return(numRow); };
>
> ...
>
> }
>
> => NUMROW FINALLY IS 6
>
When you refer to numRow in the event handler function, you create a
closure, meaning that the function has a reference to the variable
numRow - the "box" labelled "numRow", if you will. Note that this is not
the same as having a reference to the _value_ that the variable contains
at the time the closure is created; when, at a later time, the event
handler executes, it will look at the variable and find it contains the
value 6, because that is the value left there when the loop had finished
executing.To get a feel for this, add a line after your loop that sets
numRow to (say) 23; 23 is then the value the event handler will see in
there when it executes.
One way to achieve the effect you're looking for is to move the event
handler assignment into a function:
function assignFocusHandler(element, rowNumber) {
element.onfocus = function() {
products_price_return(rowNumber);
};
}
Invoke this in your loop using
assignFocusHandler(inputProductsDescription, numRows);
When the function executes, the event handler will form a closure over
the parameter rowNumber, which is a different instance of the parameter
for each invocation of the function, each instance therefore (in this
case) having a different value; and you'll get the effect you wanted.
(Of course, for consistency, you may want to call the parameter "numRow"
rather than "rowNumber"; I just chose a different name to emphasise that
within the function, it's a different "box" to the one in the calling
function, and contains a _copy_ of the value stored in numRow.)
HTH,
Nick.
--
Nick Fitzsimons
http://www.nickfitz.co.uk/
More information about the Javascript
mailing list