beeblbrox — 2010-03-26T14:42:26-04:00 — #1
Hi, I've only just started hacking around with JS, and have created a basic pop-out effect on a menu, where I wanted to make the pop-out stick when the root list element is actually clicked. It all works fine (I know it's not an ideal solution but I do like to learn through my own experimentation), but I am puzzled by the behaviour of the variable 'bit' in the following code:
// called with window.onload
The menu pops out and stays out, or pops back in and stays in, on a onclick to the root element - therefore 'bit' is remembering its value between function calls.
At first I thought that a new global variable 'bit' must be being created in the onclick anonymous function call, else how can its value be maintained between function calls, but removing the local declaration just breaks the script.
My searches for this have only returned standard global/local/private etc. explanations of variables in JS.
I'm sure this is something pretty basic but I would really appreciate some enlightenment
logic_ali — 2010-03-26T22:51:59-04:00 — #2
Not exactly basic. When a function is declared inside another, the environment around the inner function is preserved. This is called a closure, meaning that bit persists and continues to be visible to the onclick handler, without having global scope.
beeblbrox — 2010-03-26T23:00:36-04:00 — #3
Thanks ever so much for that! I did discover Closure variables in my search but the explanation was incredibly obfuscated that I wasn't sure that's what it was - thank you for clearing that up for me!
beeblbrox — 2010-03-26T23:05:20-04:00 — #4
p.s. Is this a behaviour peculiar to JS? I have some experience in a number of languages but have never come across this before.
Edit: wow - just read up on good ole wiki about this - whole new area of comp sci i was never aware of - looks like I have some studying! Thanks again!
crmalibu — 2010-03-27T22:25:28-04:00 — #5
Functional programming is a pretty cool paradigm if your looking to expand your horizons.
beeblbrox — 2010-03-27T22:43:48-04:00 — #6
Yeah I did a little ML at Uni, was very impressed with the method, to be honest though my Maths is not up to it - very heavyweight. Still, I did learn the value and use of recursion out of it though, priceless.