Yep, that looks like a mistake in the copy editing. We'll make sure that makes it into the errata list. Thanks for catching that!

Here's the original code; our copy editor changed the variable names to match the publisher's style guide.

$(document).ready(function() {
  function f() {
    var a = 0;
    function g() {
      a++;
      console.log(a);
    }
    function h() {
      a = a + 2;
      console.log(a);
    }
    return {'g': g, 'h': h};
  }
  var m = f();
  m.g();
  m.h();
  m.g();
  var n = f();
  n.g();
  n.h();
  n.g();
});


On Jul 13, 2007, at 18:16 , Guapo wrote:


the following text if copy from the book,I was confused with the
variable globVar in the innerFun2,is it a clerical error or the
variable in the statement "var globVar = outerFun();"?
thank you all!
====================================
Interactions between Closures
When more than one inner function exists, closures can have effects
that are not as easy to anticipate. Suppose we pair our incrementing
function with another function, this time incrementing by two:
function outerFun() {
        var outerVar = 0;
        function innerFun() {
                outerVar++;
                alert(outerVar);
        }
        function innerFun2() {
                outerVar = outerVar + 2;
                alert(globVar);
        }
        return {'innerFun': innerFun, 'outerFun2': outerFun2};
}
We return references to both functions, using a map to do so (this
illustrates another way in which reference to an inner function can
escape its parent). Both functions can be called through the
references:

var globVar = outerFun();
globVar.innerFun(); // Alerts "1"
globVar.innerFun2(); // Alerts "3"
globVar.innerFun(); // Alerts "4"

var globVar2 = outerFun();
globVar2.innerFun(); // Alerts "1"
globVar2.innerFun2(); // Alerts "3"
globVar2.innerFun(); // Alerts "4"


--
Jonathan Chaffer
Technology Officer, Structure Interactive


Reply via email to