binding
is a variable name (this I borrow from the previous glossary). Can be classified into one of two categories:
lexical binding
, which can be determined at the lexing step of the compilation. Any variable or function declaration in user-authored code.dynamic binding
, which can only be determined at runtime. The this
binding, i.e.normal function
is every kind of function but an arrow one. Okay, async functions
and generators
sometimes neither.Well... it’s not about execution contexts
. It’s more about what execution contexts
are not. It assumes you already know... wait, am I not just writing the same as in the previous article? I guess I just don’t know what this article is about. But it aims to go a bit deeper into the this
binding in arrow functions and explores executions context
as an inevitable side-effect. Also, worth mentioning it’s going to go as deep as my current knowledge allows me to... shit, I did it again.
Once I’ve finished writing it, I think I’ve kinda explained something about the difference between arrow and normal functions, this
and closures
.
<aside>
❓ Arrow functions don't define their own this
. In arrow functions, this
refers to the same value as this
in their outer lexical scope.
</aside>
I don't know who first described it that way, but everyone repeats it and it has always bugged me. Not because it's necessarily wrong but because, to me, it's a bad explanation.
First of all, I feel like everyone repeats it but doesn’t understand its meaning.
Second, it kinda makes it feel as if the value of this
in an arrow function could be (or even was!) determined at compile-time.
Yes, in arrow functions, this
refers to the same value as this
in their outer lexical scope. But I have two issues:
this
in their outer lexical scope, at some point you have to ask yourself what’s the value of this
in their outer lexical scope! And there’s a good chance that can’t be determined at compile-time if there’s any normal function
up in their scope chain
. So you can’t just look at a representation of the scope chain
of your code (otherwise Bubbl.es would be amazing!) and reason about the this
keyword. You most likely have to think about run-time. Simply because the this
keyword is completely pointless in an “only-arrow functions” environment.I’d like I could rephrase it as:
<aside>
✅ Arrow functions don't bind a value to this
. In arrow functions, the value of this
is resolved through a lexical lookup, as if it was a lexical binding
. But beware, the whole lookup might not be lexical.
</aside>