Hello code-mates, ever since I learnt about this
in Javascript a year ago, I had never fully felt mentally confident that I can interpret, analyse and refactor complicated scenarios where this
is used. I therefore made a small cheatsheet-like summary to always help me get the immediate context & idea, especially when I am rushing through documentations or others’ code, and obviously infiltrate well later.
Here are a few bullets I always find handy in relation to this
:
- All regular functions (
function myFunction() {}
) always have theirthis
as the globalwindow
object (in browsers) orglobal
object (in Node JS), UNLESS it is called in a different context:- As a method of an object.
- Explicitly bound by
.bind()
,.call()
or.apply()
.
- Regular functions have to be explicitly bound with a
this
value while arrow functions (() => {}
) automatically get theirthis
from the immediate enclosing parent-function (lexical scope). - The lexical/enclosing scope in which an arrow function is actually running is the immediate parent REGULAR function, even though it is inside an object’s method.
- The
this
value of arrow functions (got at time of creation) is unchangeable while that of regular functions is changeable (.bind()
,.call()
etc.) - Unlike methods of object literals (
const obj = {...}
), functions defined as methods of classes, Event though regular or arrow, theirthis
is always the object instance created (new MyClass()
)
Please feel free to suggest edits, add more bullets, or even criticize me on any blunders. I always welcome an opportunity to learn from excellent programmers like you! ☺️ 💛
Top comments (0)