In a tutorial I’m currently following, I’m currently asked to make the following test work:
[CODE]
it(‘the rule about retaining access to variables from an outer scope still applies, even after the outer function call (that created the outer scope) has returned’, function () {
var outerFn = function () {
// NOTE: the contents of this function is the same as the entire body of the previous test
var counterInOuterScope = 10;
var innerIncrementingFn = function () {
counterInOuterScope = counterInOuterScope + 1;
ACTUAL = counterInOuterScope;
};
innerIncrementingFn();
expect(ACTUAL === 11).to.be.true;
innerIncrementingFn();
expect(ACTUAL === 12).to.be.true;
// Here, we retain a reference to the newly created inner function for later, by assigning it to the global scope (window)
window.retainedInnerFn = innerIncrementingFn;
};
// before we run outerFn, there will be no innerFn exported to the global scope
expect(window.retainedInnerFn).to.equal.undefined;
// running this outer function should have the same effect as running the whole previous test, with the addition of placing the innerFn somewhere that we can reach it after outerFn has returned
outerFn();
expect(window.retainedInnerFn).to.be.a(‘function’);
// even though the outerFn has returned once the only call to it was completed a couple of lines above, the inner function remains available in the global scope, and still has access to the variables of that containing scope where it was first created.
window.retainedInnerFn();
expect(ACTUAL === 13olivi).to.be.true;
});
Based on the result it appears that a javascript function and its subfunctions remain in memory (including the values of the variables defined in its scope) even after its been called.
So when we create a reference to one of the subfunctions we can execute it outside of its original context, but still have the variables (and values) of the original call at our disposal.
Or am I mistaken here?