Originally published on php-to-js.learnio.dev — part of the PHP to JavaScript course. View this lesson on the original site.

Arrow functions inherit this from where they are written

PHP closures use use ($var) for variables. JavaScript arrows also differ from regular functions on this: they do not get a new this — they reuse the surrounding one.

PHP habit

<?php
class Panel {
    public string $title = 'Settings';

    public function demo(): void {
        $arrow = fn () => $this->title; // $this from demo()'s scope
        echo $arrow();
    }
}

PHP 7.4+ arrows automatically bind $this when used inside a method.

JavaScript equivalent

const panel = {
  title: 'Settings',
  demo() {
    const arrow = () => console.log('arrow:', this.title);
    const regular = function () {
      console.log('regular:', this?.title);
    };
    arrow();    // Settings — lexical this from demo()
    regular();  // often undefined — own this binding
  },
};
panel.demo();
Form this behaviour Default choice
function () {} New binding per call site Methods on objects, constructors
() => {} Inherits outer this Callbacks inside methods, short transforms

When arrows help

class OrderList {
  constructor() {
    this.orders = [];
  }
  onSave() {
    fetch('/api/orders')
      .then((res) => res.json())
      .then((data) => {
        this.orders = data; // this still the OrderList instance
      });
  }
}

A regular function in the inner then would need bind or storing this in a variable.

When not to use arrows

Object methods that other code calls as obj.method() should usually be regular functions or class methods — not arrows on the literal.

Try it

Use the amber Try it panel below. Click Run.

const counter = {
  value: 0,
  incRegular: function () {
    this.value += 1;
  },
  incArrow: () => {
    // this is NOT counter — lexical outer scope
    console.log('arrow this.value', this?.value);
  },
};
counter.incRegular();
console.log('after regular', counter.value);
counter.incArrow();

incRegular works; incArrow does not bump counter.value — classic arrow mistake on object methods.

From PHP to JavaScript — Control Flow, Functions, and Scope