I think you've got it! By George you've got it!

(With apologies both to you and to Rex Harrison and Audrey Hepburn!)

What you describe is not the only way to do it, but it's certainly a good
way.

You just have to understand what variables a function has access to. Of
course a function can access its own local variables and its own parameters.
A function can *also* access variables (and parameters, same thing) in any
functions that it's nested inside.

When JavaScript looks up a name, it starts in the innermost function where
the reference to the name occurs. If it doesn't find the name there, and if
the function is nested inside another function, then it looks in that outer
function. If it still doesn't find the name, and there is another outer
function, it looks there, and so on, until finally as a last resort it
reaches the global scope (which is really the window object).

It doesn't matter if the functions have names or are anonymous - all this
works the same either way.

A classic example is the use of a function with setTimeout:

function test() {
    var foo = 'bar';
    setTimeout( function() {
        alert( foo );  // alerts 'bar'
    }, 1000 );
}

As with the jQuery event examples, note that the alert call is made long
after the test() function has returned. But JavaScript keeps a reference to
the foo variable just so that the inner function can use it.

And like the jQuery examples, it works the same if you don't use an
anonymous function:

function test() {
    var foo = 'bar';
    setTimeout( alerter, 1000 );
    function alerter() {
        alert( foo );  // alerts 'bar'
    }
}

It's the fact that the alerter function is nested inside the test function
that makes it work.

This use of a nested function to access variables after an outer function
has returned is called a "closure". It's one of the most powerful features
in JavaScript, and one to get very familiar with.

-Mike

On Sat, Dec 12, 2009 at 11:10 AM, Jojje <jojjsus_chr...@hotmail.com> wrote:

> Oh ok :)
>
> So in order for me to pass arguments without triggering
> clickFunction1  immediately,and instead triggering it when the link is
> clicked,  i have to call it through another function thats not passed
> any arguments? So it´s still ok to use an anonymous function like in
> my example to achieve this? The reason i´m asking this is i´m still
> learning the fundamentals of javascript and i don´t know how the
> computer handles the code, If it takes up more memory and so on. :)
> Thank you so much for taking time to answer these questions, highly
> appreciate it :)
>
> Regards
>
> George
>

Reply via email to