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

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more