Lexical this in arrow functions
We discussed ES6 arrow functions and the syntax in detail in the last chapter. However, an important aspect of arrow functions is that they behave differently from normal functions. The difference is subtle but important. Arrow functions do not have their own value of this
. The value of this
in an arrow function is inherited from the enclosing (lexical) scope.
Functions have a special variable this
that refers to the object via which the method was invoked. As the value of this
is dynamically given based on the function invocation, it is sometimes called dynamic this
. A function is executed in two scopes-lexical and dynamic. A lexical scope is a scope that surrounds the function scope, and the dynamic scope is the scope that called the function (usually an object)
In JavaScript, traditional functions play several roles. They are non-method functions (aka subroutines or functions), methods (part of an object), and constructors. When functions do the duty of a...