Variables accessible from within a function passed as parameter to Event.observe() (prototype.js). Why?

≯℡__Kan透↙ 提交于 2019-12-12 03:52:16

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!