DEV Community

Cover image for Regular this, Arrow this (Tersely bulleted)
Dhokia Rinidh
Dhokia Rinidh

Posted on

1

Regular this, Arrow this (Tersely bulleted)

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 their this as the global window object (in browsers) or global 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 their this 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, their this 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! ☺️ 💛

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay