Thanks Mike, I generally understand closures and your explanation was
very good.

I think what your saying is that the example "pen" object is just a
local variable to the ready callback.

Thanks for clearing that up...


On Oct 24, 10:51 pm, Michael Geary <m...@mg.to> wrote:
> The concept you're looking for is called a "closure". Search for:
>
> javascript closure
>
> and you will find all sorts of information about closures.
>
> It really has nothing to do with jQuery or the DOM. Closures are part of the
> core JavaScript language and work in any environment where JavaScript is
> implement. For example, Adobe Acrobat supports JavaScript, but it has no
> HTML-oriented DOM, and certainly no jQuery. But closures work exactly the
> same in JavaScript code in a PDF file as they do in a web page.
>
> Here's a simple way to understand closures:
>
> 1. When you nest one function inside another, the inner function can read
> and write variables declared in the outer function.
>
> 2. That *always* works, even if the outer function has already completed
> running and returns to its caller.
>
> That's what is happening in your example: You have an outer function - the
> "ready" callback - and an inner function - the "click" handler. The inner
> function can access the variable declared in the outer function, even though
> the inner function runs long after the outer function has returned.
>
> -Mike
>
> On Sat, Oct 24, 2009 at 5:23 PM, Nikola <nik.cod...@gmail.com> wrote:
>
> > It has to be stored somewhere though...
>
> > Say, for example, we bind a handler to the click event on the BODY of
> > the document and we log the "pen" object to the console.
>
> > $(function(){
>
> >        var pen =
> >        {
> >                        type: "Ballpoint",
> >                        color: "blue",
> >                        hasInk: true
> >        }
>
> >         $("BODY").click(function(){
> >                console.log(pen)
> >        })
>
> > });
>
> > As you can see when you run that code, the "pen" object is logged to
> > the console so it has to be stored somewhere...
>
> > Where, is the question.
>
> > On Oct 24, 8:01 pm, donb <falconwatc...@comcast.net> wrote:
> > > You can't.  It exists for the duration of the ready function, then
> > > it's gone.
>
> > > On Oct 24, 7:51 pm, Nikola <nik.cod...@gmail.com> wrote:
>
> > > > Hi, I've been trying to understand a little tidbit of jQuery here...
>
> > > > Lets say we define an object in the Document "ready" method:
>
> > > > $(function(){
>
> > > >         var pen =
> > > >         {
> > > >                 type: "Ballpoint",
> > > >                 color: "blue",
> > > >                 hasInk: true
> > > >         }
>
> > > > });
>
> > > > Where in the DOM can we find the pen object?

Reply via email to