...

/

Lexically Scoped this and arguments

Lexically Scoped this and arguments

Learn the lexical behavior of this and arguments in arrow functions and their dynamic behavior in anonymous functions.

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.

Press + to interact
Javascript (babel-node)
'use strict';
//START:THIS
this.stuff = 'from lexical scope';
const someValue = 4;
const self = this;
setTimeout(function() {
console.log('someValue is ' + someValue); //lexical scope for someValue
console.log('this...' + this.stuff); //dynamic scope for this
console.log('self...' + self.stuff); //lexical scope for self
}, 1000);
//END: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: The someValue variable has lexical scope inside the anonymous function, so
...