Lexically Scoped this and arguments
Explore how arrow functions in JavaScript provide lexical scoping for this and arguments, unlike anonymous functions that use dynamic scoping. Understand the common pitfalls with this and arguments in traditional functions and learn when to prefer arrow functions or use rest parameters for cleaner, more predictable code.
We'll cover the following...
Lexical scoped this
Anonymous functions use dynamic scoping for this and arguments and use lexical scoping for all other variables. This behavior often causes error and unpleasant workarounds. Recall that rest parameters are preferable to arguments in modern JavaScript, but the this keyword is still a nemesis.
Dynamic scoped this in anonymous functions
Let’s look at an example that illustrates the odd behavior of this.
Logic behind the code
Outside of the anonymous function, we have assigned a value 'from lexical scope' to the stuff property of this at line 4—the context object. We also created a local variable named someValue and a variable named self. Then, we assigned the this reference to self at line 6.
Within the anonymous function passed to setTimeout(), we have not defined someValue, this, or self, but we readily use them anyway. Let’s look at the above code’s output.
someValue: ThesomeValuevariable has lexical scope inside the anonymous function, so