O'Reilly logo

Learning jQuery Third Edition by Karl Swedberg, Jonathan Chaffer

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 one incrementing by two:

function outerFn() {
  var outerVar = 0;
  function innerFn1() {
    outerVar++;
    $.print('(1) outerVar = ' + outerVar);
  }
  function innerFn2() {
    outerVar += 2;
    $.print('(2) outerVar = ' + outerVar);
  }
  return {'fn1': innerFn1, 'fn2': innerFn2};
}
var fnRef = outerFn();
fnRef.fn1();
fnRef.fn2();
fnRef.fn1();
var fnRef2 = outerFn();
fnRef2.fn1();
fnRef2.fn2();
fnRef2.fn1();

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required