this and Arrow Functions in JavaScript
Introduction
this refers to the execution context—often the object before the dot when you call a method. Arrow functions do not have their own this; they inherit from the surrounding scope. Mixing them incorrectly breaks event handlers and class methods—this chapter shows the rules and fixes.
Prerequisites
this in Methods
// this points to the object for method calls
const counter = {
value: 0,
increment() {
this.value += 1;
return this.value;
},
};
counter.increment();
console.log(counter.value);Losing this — Common Bug
// Extracted method loses binding
const player = {
name: "Ada",
greet() {
console.log(`Hi, ${this.name}`);
},
};
const fn = player.greet;
fn();Warning
Calling fn() without player. makes this undefined (strict mode) or the global object (sloppy mode in browsers).
Fix with bind
// bind fixes this permanently
const boundGreet = player.greet.bind(player);
boundGreet();Arrow Functions Lexical this
// Arrow uses this from outer scope
const timer = {
seconds: 0,
start() {
setInterval(() => {
this.seconds += 1;
console.log(this.seconds);
}, 1000);
},
};
// timer.start(); // uncomment to run in Node/browserClassic function inside start would need const self = this or bind.
When Not to Use Arrows as Methods
// Bad: arrow method — this is NOT timer
const broken = {
value: 0,
tick: () => {
this.value += 1;
},
};
broken.tick();
console.log(broken.value);Use method shorthand tick() { } on objects.
Arrow Syntax Recap
// One param, expression body
const inc = (n) => n + 1;
// Multiple params or block body
const max = (a, b) => (a > b ? a : b);
const logPair = (a, b) => {
console.log(a, b);
};
console.log(inc(1), max(3, 7));
logPair("x", "y");No arguments in Arrows
Use rest instead: (...args) => args.length.
Mini Example: Button Handler Pattern
// Object with handler using arrow in constructor-style setup
function createButton(label) {
return {
label,
clicks: 0,
handleClick() {
this.clicks += 1;
console.log(`${this.label}: ${this.clicks}`);
},
};
}
const btn = createButton("Save");
btn.handleClick();
btn.handleClick();FAQ
Should React components use arrows?
Class components used arrow class fields for this; function components with hooks avoid this entirely.
Does arrow bind this with call?
No—call/apply/bind cannot change arrow this.
Strict mode?
Modules and modern scripts are strict—this is undefined in loose calls to plain functions.