Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Callbacks for events on webpages

...

Code Block
languagecss
titlecss snippet
linenumberstrue
body {
  font-family: Helvetica, Arial, sans-serif;
  font-size: 12px;
}

h1 {
  font-size: 1.5em;
}

h2 {
  font-size: 1.2em;
}

In the example the interactive text size buttons can change the font-size property of the body element, and the adjustments will be picked up by other elements on the page thanks to the relative units.

The javascript to do this is shown here

...

Code Block
languagejs
titleexample js code
linenumberstrue
var counter = (function() {
  var privateCounter = 0;
  bb = function changeBy(val) {
    privateCounter += val;
  }
  debugger;
  bb(3);
  return {
    increment: function() {
      changeBy(1);
    },
    decrement: function() {
      changeBy(-1);
    },
    value: function() {
      return privateCounter;
    }
  };   
})();
debugger;
alert(counter.value()); // logs 0
counter.increment();
counter.increment();
alert(counter.value()); // logs 2
counter.decrement();
alert(counter.value()); // logs 1

...

  • within a lexical environment, a value assigned to a variable that s not prefixed with var is globally available, so it pollutes the global namespace
  • within a lexical environment, a value assigned to a var variable is not globally available
  • within a lexical environment, a function that is assigned to variable (with or without var) is not available outside of the lexical environment unless it is returned using the return keyword, such a function is private

In the above example the closure changeBy has been assigned to the variable bb.  If you change the calls to changeBy() at lines 9 and 12 to bb() no exception is thrown and the code works.  It would seem that <variable> = function <func_name>(...) {...}, <func_name> is hidden and you have to use <variable_name>() instead!

Ok, so let's do a little experiment and see what happens, consider the following piece of code

Code Block
languagejs
titleexample js code
linenumberstrue
function increment( val )
{
   return ++val;
}

alert( increment( 2 ) );

This works fine.  But if we change the code to

Code Block
languagejs
linenumberstrue
bb = function increment( val )
{
   return ++val;
}

alert( increment( 2 ) );

This fails.  But if we change it to

Code Block
languagejs
titleexample js code
linenumberstrue
bb = function increment( val )
{
   return ++val;
}

alert( bb( 2 ) );

This works.  Why why why???