I just read the Wikipedia article on closures[1] today and learned quite a bit myself (which isn't saying much!). I would recommend it to anyone wanting to learn more about it. To quote a portion:
"[...] a closure is a semantic concept referring to a function paired with an environment [...] Typically, a closure occurs when one function appears entirely within the body of another, and the inner function refers to local variables of the outer function. At runtime, when the outer function executes, a closure is formed, consisting of the inner function's code and references to any variables of the outer function required by the closure [...] " [1] http://en.wikipedia.org/wiki/Closure_%28computer_science%29 On 4/18/07, Rob Desbois <[EMAIL PROTECTED]> wrote:
17By creating a function form your code which uses variables outside its scope, you've created a 'closure'. When settings.functionToCallLater() is called after init() has finished, aVariable has gone out of scope. The function still has access to it however, because the closure consists of two parts: the code of the function itself, and a reference to all variables outside its scope that it needs access to. Have a search on Google for 'javascript closures', there are plenty of good articles that can explain this more fully than me. HTH, rob On 4/18/07, Ariel Jakobovits <[EMAIL PROTECTED]> wrote: > > > this isn't the real code, just a mockup, but ... > > can someone explain to me why this works (as in, alert echoes 'ariel'): > > var temp = null; > > function init () > { > > var aVariable = 'ariel'; > > var settings = { > functionToCallLater: function (content) { > alert(aVariable); > } > }; > > temp = new anotherClass(settings); > } > > anotherClass.callThatFunction (); > > > > -- Rob Desbois Eml: [EMAIL PROTECTED] Tel: 01452 760631 Mob: 07946 705987 "There's a whale there's a whale there's a whale fish" he cried, and the whale was in full view. ...Then ooh welcome. Ahhh. Ooh mug welcome.