/    Sign up×
Community /Pin to ProfileBookmark

Newbie question regarding scope

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;
});
[/CODE]

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?

to post a comment
JavaScript

0Be the first to comment 😎

×

Success!

Help @fysicus spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.16,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @nearjob,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...