Emmanuel Akinfulubi

JavaScriptBasic

Arrow function vs regular function: this in JavaScript

Advanced · 4 min read

Inside a function, the word this usually means "the object this function was called on". It lets a method reach its own object's data, the way trip.labels() can read trip.stops. The confusing part is that this works differently in the two kinds of function JavaScript has: the plain function and the arrow =>. Mix them up and this suddenly points at nothing, and your code throws.

In this tutorial you will give a trip object a method that maps over its own stops. You will write the inner callback as an arrow, then as a plain function, and see which one can still reach the trip. Then you will pull the method off the object, watch it break, and fix it with call and bind. You need to know what objects, methods and map are. Nothing else is assumed.

A plain function gets this from the call

For a plain function (and a method written as labels() { ... }), this is decided at the moment of the call, by what is in front of the dot:

  • trip.labels(): there is a trip. in front, so this is trip.
  • labels() on its own: nothing in front, so this is undefined.

Where the function was written doesn't matter. Only how it was called.

An arrow has no this of its own

An arrow function doesn't get its own this at all. When it uses this, it borrows the one from the code around it, the place where the arrow was written, and keeps it forever.

A note on strict mode

The snippets below start with 'use strict';. Strict mode is a safer setting of JavaScript, and it is always on in modules, in classes, and in this page's answer panel. In strict mode, a bare call gives this the value undefined, so mistakes throw an error instead of quietly misbehaving.

Here is the exercise. Try it yourself first if you like, or read on and we will build it together.

93 Arrow or function, and what this points at

hard

Give an object a method that maps over its own data. Write the callback as an arrow, then as a plain function, and see which one can still reach the object. Then detach the method from the object and call it.

Stuck? Three hints, smallest first
  1. 1. A plain function gets a fresh this from the way it was called, which for a bare call is nothing.
  2. 2. An arrow has no this of its own; it uses the one from where it was written.
  3. 3. map takes a second argument that sets this for the callback.

Step 1: a method with an arrow callback

Step 1

'use strict';
const trip = {
  prefix: 'stop:',
  stops: ['Yaba', 'Ojota', 'Ikeja'],
  labels() {
    return this.stops.map((stop) => this.prefix + stop);
  },
};
console.log(trip.labels()); // [ 'stop:Yaba', 'stop:Ojota', 'stop:Ikeja' ]

trip.labels() is called with trip. in front, so inside labels, this is the trip. The arrow passed to map has no this of its own, so it uses the one from labels, which is the trip. Both this.stops and this.prefix work.

Step 2: the same callback as a plain function

Now write the callback with function instead:

Step 2

'use strict';
const trip = {
  prefix: 'stop:',
  stops: ['Yaba', 'Ojota', 'Ikeja'],
  labelsBroken() {
    return this.stops.map(function (stop) {
      return this.prefix + stop;
    });
  },
};
try {
  trip.labelsBroken();
} catch (err) {
  console.log(err.name); // TypeError
}

this.stops on the first line still works: that this belongs to labelsBroken, which was called on the trip. But the inner function gets its own this, decided by how map calls it. map calls it bare, with nothing in front, so this is undefined, and reading undefined.prefix throws a TypeError.

Step 3: the fix before arrows existed

map takes an optional second argument: the value to use as this inside the callback. Pass the trip:

Step 3

'use strict';
const trip = {
  prefix: 'stop:',
  stops: ['Yaba', 'Ojota', 'Ikeja'],
  labelsBound() {
    return this.stops.map(function (stop) {
      return this.prefix + stop;
    }, this);
  },
};
console.log(trip.labelsBound()); // [ 'stop:Yaba', 'stop:Ojota', 'stop:Ikeja' ]

This works, and you'll see it in older code, along with var self = this;. Today an arrow callback, as in Step 1, is the simple answer.

Step 4: a detached method

Copy the method into a variable and call it on its own:

Step 4

'use strict';
const trip = {
  prefix: 'stop:',
  stops: ['Yaba', 'Ojota', 'Ikeja'],
  labels() {
    return this.stops.map((stop) => this.prefix + stop);
  },
};
const detached = trip.labels;
try {
  detached();
} catch (err) {
  console.log(err.name); // TypeError
}
console.log(detached.call(trip)[0]); // stop:Yaba
const bound = trip.labels.bind(trip);
console.log(bound()[2]); // stop:Ikeja

detached is the very same function, but called with nothing in front of it, so this is undefined and this.stops throws. This happens a lot when you pass a method as a callback, for example to setTimeout(trip.labels, 1000).

Two ways to put the object back:

  • fn.call(obj) calls the function once with this set to obj.
  • fn.bind(obj) returns a new function with this fixed to obj for good.

Step 5: an arrow keeps its this forever

An arrow made inside a method captures that method's this when it is created:

Step 5

'use strict';
const depot = {
  tag: 'depot',
  makeReader() {
    return () => this.tag;
  },
};
const reader = depot.makeReader();
console.log(reader());                               // depot
console.log(reader.call({ tag: 'somewhere else' })); // depot

reader is called bare, yet it still says 'depot'. And call can't change its this: an arrow ignores the value passed in. bind and apply can't change it either.

Step 6: where arrows don't belong

Because an arrow borrows this from where it was written, an arrow written directly as a method, labels: () => this.stops, borrows the this from outside the object. That is never the object. Use the short method syntax labels() { ... } for methods, and arrows for callbacks inside them.

Arrows also can't be used with new:

Step 6

'use strict';
const Arrow = () => {};
try {
  new Arrow();
} catch (err) {
  console.log(err.name); // TypeError
}

The full solution

The answer panel has the three versions of the method, the detached call with call and bind fixes, the depot reader that ignores call, and the arrow that can't be used with new. Press Run to see the output.

The answer

const trip = {
  prefix: 'stop:',
  stops: ['Yaba', 'Ojota', 'Ikeja'],

  // The arrow inherits this from labels(), where it is the trip.
  labels() {
    return this.stops.map((stop) => this.prefix + stop);
  },

  // A plain function gets its own this. In strict mode that is undefined.
  labelsBroken() {
    try {
      return this.stops.map(function (stop) {
        return this.prefix + stop;
      });
    } catch {
      return 'threw: this was not the trip';
    }
  },

  // map's second argument is the this to use. The pre-arrow fix, still valid.
  labelsBound() {
    return this.stops.map(function (stop) {
      return this.prefix + stop;
    }, this);
  },
};

const detached = trip.labels;
let detachedError = '';
try {
  detached();
} catch (err) {
  detachedError = err.name;
}

const bound = trip.labels.bind(trip);

// An arrow captures this once, at creation, and nothing can move it afterwards.
const depot = {
  tag: 'depot',
  makeReader() {
    return () => this.tag;
  },
};
const reader = depot.makeReader();

let notAConstructor = false;
const Arrow = () => {};
try {
  new Arrow();
} catch {
  notAConstructor = true;
}

console.log(trip.labels());
console.log('detached call threw a', detachedError);

Output


      
9 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('a method sees the object it was called on', trip.labels(), ['stop:Yaba', 'stop:Ojota', 'stop:Ikeja']);
test('an inner plain function does not', trip.labelsBroken(), 'threw: this was not the trip');
test('map\u2019s second argument fixes it', trip.labelsBound(), ['stop:Yaba', 'stop:Ojota', 'stop:Ikeja']);
test('a detached method loses the object entirely', detachedError, 'TypeError');
test('call hands it back for one call', detached.call(trip)[0], 'stop:Yaba');
test('bind makes that permanent', bound()[2], 'stop:Ikeja');
test('an arrow keeps the this it was created with', reader(), 'depot');
test('and call cannot move it', reader.call({ tag: 'somewhere else' }), 'depot');
test('an arrow is not a constructor either', notAConstructor, true);

this in a plain function is decided by the call, not by where the function was written: trip.labels() sets it to trip, and the bare detached() sets it to undefined, which is why reading this.stops throws a TypeError. The old var self = this dance existed entirely to smuggle the outer this past that rule.

An arrow has no this of its own, so it reads the enclosing scope's — permanently. That makes it right for callbacks inside a method, as in labels, and wrong for the method itself: an arrow written directly in an object literal captures whatever this was outside the object, which is never the object. reader.call({...}) being ignored is the proof that call, apply and bind have no purchase on an arrow. Arrows also have no arguments, no prototype, and cannot be called with new.

Common mistakes

  • Using a plain function callback inside a method. It gets its own this. Use an arrow.
  • Writing a method as an arrow. labels: () => ... can't see the object. Use labels() { ... }.
  • Passing a method as a callback. setTimeout(trip.labels) loses the object. Pass trip.labels.bind(trip) or () => trip.labels().

Try it yourself

  1. Add a method count() to trip that returns this.stops.length, then call it detached and with call.
  2. Write labelsSelf() using the old pattern const self = this; and a plain function callback.
  3. Make depot.makeReader return a plain function instead of an arrow. What does reader() do now, and what does reader.call({ tag: 'x' }) return?

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.