At this link, Mozilla explains what ‘this’ references in the following way:
In general, the object bound to
thisin the current scope is
determined by how the current function was called, it can’t be set by
assignment during execution, and it can be different each time the
function is called.
Under normal circumstances, I understand this and how its reference changes.
The book Pro JavaScript Design Patterns says the following about lexical scope
JavaScript is also lexically scoped, which means that functions run in
the scope in which they are defined, not the scope they are executed
in.
So ‘this’ depends on how the current function was called, while lexical scope means functions are run in the scope in which they are defined.
My question is, can this ever be part of the lexical scope, and, if so, how do I understand the fact that this depends on how the current function was called, while lexical scope restricts functions to the scope in which they are defined.
Just think of them as separate concerns.
The variable scope of a function will never change.
The value of
thiswill change depending on how the function is invoked. Given the same function, different invocations give the same function a differentthis.All the invocations have access to the
barvariable, but a differentthisvalue.So given the current function syntax in ECMAScript,
thiswill never be taken from the lexical scope, but will always be assigned a value based on the invocation.There’s a new function syntax in the works that will likely have a lexical
this, but that’s sometime in the future.