Search code examples
javascriptprototypejsscope

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


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>

Solution

  • 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();
      console.log('from outer: ' + v);
      function inner () {
        console.log('from inner: ' + v);
      }
    }
    
    try {
      outer();
      console.log('from global: ' + v);
    } catch (e) {
      console.log(e.message);
    }

    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)