Skip to content

Understanding the Keyword 'THIS' in JavaScript

Inside a function, this refers to an object that the function can work on. For an ordinary function, this is not fixed when the function is written, because JavaScript decides it each time the function is called, from the way it is called. Arrow functions are the exception, since they take this from the code around them. Most confusion about this comes from expecting it to follow where a function was defined rather than how it was called.

When a function is called as a method, with an object and a dot before it, this is that object:

const thermostat = {
room: 'Kitchen',
target: 20,
report() {
return `${this.room} is set to ${this.target}°C`;
},
};
console.log(thermostat.report());
const hall = { room: 'Hall', target: 17, report: thermostat.report };
console.log(hall.report());

This prints:

Kitchen is set to 20°C
Hall is set to 17°C

The same function gives a different answer when it is called through hall, because this comes from the object before the dot at the moment of the call.

When a function is called on its own, with nothing before it, there is no object to use. In sloppy mode this is then the global object, while in strict mode it is undefined:

function whoAmI() {
return this === globalThis;
}
function whoAmIStrict() {
'use strict';
return this;
}
console.log(whoAmI());
console.log(whoAmIStrict());

This prints:

true
undefined

This example runs as a sloppy-mode script, and a browser’s classic script behaves the same way, with this equal to window. Modules and classes are always strict, so there this in a plain call is always undefined.

Losing this, and fixing it with bind or call

Section titled “Losing this, and fixing it with bind or call”

Taking a method off its object and calling it later is the usual way this gets lost, because the later call has nothing before the dot. bind() returns a copy of the function with this fixed, and call() runs the function once with whatever this it is given:

'use strict';
const thermostat = {
room: 'Kitchen',
target: 20,
report() {
return `${this.room} is set to ${this.target}°C`;
},
};
const report = thermostat.report;
try {
report();
} catch (err) {
console.log(err.message);
}
const bound = thermostat.report.bind(thermostat);
console.log(bound());
console.log(thermostat.report.call({ room: 'Loft', target: 15 }));

This prints:

Cannot read properties of undefined (reading 'room')
Kitchen is set to 20°C
Loft is set to 15°C

The same problem appears when a method is passed as a callback, such as to setTimeout. Call, Apply and Bind covers these three methods in detail.

An arrow function has no this of its own. It uses the this of the code it was written inside, and neither the way it is called nor call() or bind() can change that. This makes arrow functions the right choice for a callback inside a method:

const thermostat = {
room: 'Kitchen',
readings: [19, 20, 21],
logAll() {
this.readings.forEach((r) => {
console.log(`${this.room}: ${r}`);
});
},
logAllBroken() {
this.readings.forEach(function (r) {
console.log(`${this.room}: ${r}`);
});
},
};
thermostat.logAll();
thermostat.logAllBroken();

This prints:

Kitchen: 19
Kitchen: 20
Kitchen: 21
undefined: 19
undefined: 20
undefined: 21

In logAll, the arrow function takes this from logAll, which is thermostat. In logAllBroken, the ordinary function is called by forEach as a plain function, so this is the global object, which has no room. For the same reason, an arrow function should not be used as a method itself, because it would not see the object it is attached to.

In the browser, an ordinary function used as an event listener gets the element it is attached to as this, while an arrow function keeps the this of the surrounding code:

const button = document.querySelector('#save');
button.addEventListener('click', function () {
this.textContent = 'Saved';
});
button.addEventListener('click', () => {
console.log(this === button);
});

When the button is clicked, the first listener changes the button’s text to “Saved”, because this is the button. The second logs false, because the arrow function’s this comes from the surrounding script rather than from the button. Inside either kind of listener, event.currentTarget refers to the element too, and it does not depend on the kind of function.

Steve Griffith covers this topic in his video Understanding the Keyword THIS in JavaScript.