On Jan 19, 11:31 pm, Ran Berenfeld <[email protected]> wrote:
> Hello all
>
> sorry for this stupid question, but all these talks about the "*this"
> pointer and the variable
> scope in js got me confused.

A function's this keyword has nothing to do with scope.

> support I have 2 functions, one calling the other inside array iteration.
> can they both
> use the same local variable for array index ?

Yes, if that's what you want to do. There are a number of ways to do
that.

> should I use a "var" statement ?

Yes, always.

>
> for example :
>
> function B()

By convention, function names starting with a captial letter are
reserved for constructors.


> {
>    for(i=0;i<array_b_length;i++)

You should declare i as a local variable (and I think you have a typo
with array_b_lengh), so:

    for (var i=0; i < array_b.length; i++)

Variables that aren't declared locally become global variables at the
point in execution when the statement that creates them is executed.
If neither A or B are called, or if the for loops are never executed,
this code will not create a global i variable.

>    {
>        ...
>    }
>
> }
>
> function A()
> {
>    for(i=0;i<array_a.length;i++)
>    {
>       B()
>       ...
>    }
> }

If this code is run unmodified, when A is called a global variable i
will be created. When A calls B, it will access the same variable.
Since the for loop in B initially assigns 0 to i, its loop will run
OK, but when control returns to A, the value of i will be whatever it
was when B finished with it (in this case, array_b.length). So if
array_a.length <= array_b.length+1 then the for loop in A will only
run one loop.


--
Rob

-- 
You received this message because you are subscribed to the Google Groups 
"Prototype & script.aculo.us" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/prototype-scriptaculous?hl=en.

Reply via email to