Read up on the specs of how js is required to parse and execute - this behavior is defined there.
When entering an execution context (either the global scope or function), all variables declared with 'var' are parsed before any execution actually begins. So just because 'var $inner' appears at the end doesn't mean anything. The compiler actually finds it first, creates a new variable in the current scope, then begins executing the function. Otherwise, if you had code like this: function() { myVar = 5; var myVar = 6; } the first line would alter the global (or containing) scope, while the second would be local to the function. However, in reality since the 'var' is found first, both variables refer to the same item. This is a reason why it is common and recommended practice to declare all local variables at the top of a function, using 'var', so it is very clear. Matt Kruse On Sep 14, 5:15 am, ajp <alistair.po...@gmail.com> wrote: > I didn't expect this to work (with my 'compiler' hat on) but it does: > > var clickFunction = function() { $inner.doSomething() }; > $("div") > .append("<div id=inner>bla</div>") > .click(clickFunction); > > var $inner = $div.find("#inner"); > > I was expecting an error for $inner to be undefined when the > javascript parsed the first line, but the browser script engines seems > quite happy with this sort of super-late declaration. --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "jQuery Development" group. To post to this group, send email to jquery-dev@googlegroups.com To unsubscribe from this group, send email to jquery-dev+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/jquery-dev?hl=en -~----------~----~----~----~------~----~------~--~---