问题
I have the following working JS script in one of the sites I'm working on. I'm wondering why the variables 'countryEl' and 'zipEl' are accessible from within the function passed to Event.observe. Can anybody explain?
Thanks in advance!
<script type="text/javascript">
//<![CDATA[
document.observe("dom:loaded", function() {
var form = $('shipping-zip-form');
var countryEl = form.down('#country');
var zipEl = form.down('#postcode');
Event.observe(countryEl, 'change', function () {
var selectedValue = $(countryEl).getValue();
if (selectedValue == 'US') {
zipEl.addClassName('validate-zip-us');
}
else {
zipEl.removeClassName('validate-zip-us');
}
});
});
//]]>
</script>
回答1:
If it did not, life would be so much harder. Apparently the private vars in document.observe are still local inside the Event.observe possibly passed on by some jugglery of the api. But would you rather not have it that way? How would that be of help I cannot imagine.
回答2:
The following code snippet demonstrates that the variable "v" is only accessible from the context in which it was defined, that is to say the context of the "outer" function. Hence, functions defined inside this context can access "v" as well.
function outer () {
var v = 'hello!';
inner();
log('from outer: ' + v);
function inner () {
log('from inner: ' + v);
}
}
try {
outer();
log('from global: ' + v);
} catch (e) {
log(e);
}
<script>function log(s){document.body.innerHTML+=s+'<br>'}</script>
More: http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html.
Additional note
The combination of the "inner" function and the environment is called a "closure". I'm still a bit confused regarding the exact definition. Some might use this term to designate the "inner" function itself, but it sounds more like a misuse. Here is what MDN says:
Closures are functions that refer to independent (free) variables. In other words, the function defined in the closure 'remembers' the environment in which it was created. (MDN)
A closure is a special kind of object that combines two things: a function, and the environment in which that function was created. (MDN)
来源:https://stackoverflow.com/questions/19446101/variables-accessible-from-within-a-function-passed-as-parameter-to-event-observe