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! ☺️ 💛

Billboard image

Monitor more than uptime.

With Checkly, you can use Playwright tests and Javascript to monitor end-to-end scenarios in your NextJS, Astro, Remix, or other application.

Get started now!

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay