JavaScript execution context — scope chain, closure, and this (part 4)

  • closure
  • this

Variable lookup

A variable lookup could be confusing in the following example.

  • the isBananafunction execution context
  • the isApplefunction execution context

Outer

Our chain lookup missed a critical component in the execution context, the outer.

Lexical scope

JavaScript engine has a rule: the lexical scope is defined by where the function located.

  • function priceB is defined in the priceA scope;
  • function priceC is defined in the priceB scope.
  • In priceB execution context, the outer points topriceA execution context;
  • In priceA execution context, the outer points to the global execution context.

Closure

The closure is more straightforward to understand than it sounds. Let’s take a look at an example.

“This” is not part of a scope chain

We have touched three components in an execution context:

  • lexical environment
  • outer

Who is “this”?

Let’s take a look at an example.

Convert this to the scope concept

Though the this has nothing to do with the scope, we can easily convert it to the scope concept.

What are the takeaways?

  • The outer defined the variable chain lookup, AKA, the scope chain.
  • The lexical scope defines the outer, and where you write functions sets the lexical scope.
  • The scope chain is determined at the compiling step, not the execution step. Hence, a function call, which happens at the execution step, doesn’t affect the scope chain.
  • The closure appears because of the lexical scope rule — an inner function can always access to variables in its outer function. It is exclusive to the functions holding the variable references.
  • this is not a scope concept. Whoever calls the function (or method) is this.

Further reading

  • This is a post about the execution context. You can find more information about the outer.
  • If you are interested in some extensive reading, this post is talking beyond the JavaScript call stack.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store