JavaScript · Lesson 4
How this Works
In JavaScript, this is decided by how a function is called, not where it's written; four rules plus arrow functions explain every case, including the lost-this bugs in callbacks and class methods.
In short
thisis set by the call, not by where the function is written- Check in order:
new, thencall/apply/bind, thenobj.method(), then a plain call - A plain call gets
undefinedin strict mode - Passing
obj.methodas a callback losesthis - Arrow functions use the surrounding
this;bindfixes it for good
In C#, this always means "the object this method belongs to". In JavaScript, it doesn't. For a normal
function, this is an extra, hidden argument that the caller passes, and it's decided by how the
function is called, at the moment it's called. The same function can see a different this every time.
That one sentence explains every this bug you'll meet: a method that works when called as
user.greet() and crashes when passed to setTimeout, a React class handler that loses its component,
an Angular callback that suddenly can't find this.http. This lesson gives you the four rules, the arrow
function exception, and the fixes, and then the exercises have you rebuild bind itself.
Snippets run in strict mode (like modules and classes do), which is what modern code uses. Every js
snippet has a ▶ Try button.
The mental model: look at the call site
To find this, don't look at where the function is defined. Find where it's called and ask which of
these four rules applies.
| Rule | Call looks like | this is |
|---|---|---|
new | new User('ann') | the brand new object |
| Explicit | fn.call(obj), fn.apply(obj), fn.bind(obj)() | obj |
| Implicit (method call) | obj.fn() or obj['fn']() | obj, the thing before the dot |
| Default | fn() | undefined (in sloppy mode: the global object) |
If several could apply, the one higher in the table wins. Arrow functions ignore all four: they
don't have their own this at all.
Rule 1: default binding
A plain call, with nothing before the dot, gets this === undefined in strict mode.
function whoAmI() {
return this;
}
console.log(whoAmI()); // undefined
In old, non-strict scripts, this would be the global object (window in a browser), so
this.name = 'x' silently created a global variable. Strict mode turned that silent bug into a loud one.
ES modules and class bodies are always strict, so undefined is what you'll see in modern code.
Rule 2: implicit binding (method calls)
When you call a function as a property of an object, this is that object.
const user = {
name: 'Ann',
greet() {
return `Hi, I'm ${this.name}`;
},
};
console.log(user.greet());
// the same function on another object gets another `this`
const admin = { name: 'Root', greet: user.greet };
console.log(admin.greet());
The function isn't "owned" by user. It's just a value stored in a property. Only the last object before the
call matters: in app.session.user.greet(), this is app.session.user.
Losing this
Here's the bug everyone hits. The moment you take the function off the object and call it some other way, the dot is gone, so you fall back to rule 1:
const user = {
name: 'Ann',
greet() {
return `Hi, I'm ${this.name}`;
},
};
const greet = user.greet; // just the function, the object is not attached
try {
greet();
} catch (e) {
console.log('detached:', e.message);
}
const { greet: destructured } = user; // destructuring does the same
try {
destructured();
} catch (e) {
console.log('destructured:', e.message);
}
// passing it as a callback is the same thing: forEach calls it as a plain function
try {
['x'].forEach(user.greet);
} catch (e) {
console.log('callback:', e.message);
}
The usual places this happens:
- Callbacks:
setTimeout(this.tick, 1000),items.forEach(this.process),promise.then(this.handle),observable.subscribe(this.onNext). - Event handlers:
button.addEventListener('click', this.onClick)(the DOM then calls it with the button asthis, which is worse thanundefinedbecause it doesn't crash right away). - Destructuring methods out of an object or class instance.
A plain function passed to setTimeout is never called on your object: this is window in a browser, a
Timeout object in Node, and undefined in this lab.
Rule 3: explicit binding with call, apply and bind
Every function has three methods to set this yourself:
function introduce(greeting, punctuation) {
return `${greeting}, I'm ${this.name}${punctuation}`;
}
const ann = { name: 'Ann' };
console.log(introduce.call(ann, 'Hello', '!')); // call: arguments one by one
console.log(introduce.apply(ann, ['Hey', '?'])); // apply: arguments as an array
const annIntro = introduce.bind(ann, 'Hi'); // bind: a NEW function, `this` fixed for good
console.log(annIntro('.'));
console.log(annIntro.call({ name: 'Bob' }, '.')); // still Ann: bind wins over call
callandapplycall the function now. The only difference is how you pass arguments ("apply takes an array"). With spread syntax,call(obj, ...args)covers most uses ofapply.binddoesn't call anything. It returns a new bound function whosethisis fixed (onlynewoverrides it), and it can also fix leading arguments (partial application). Binding a bound function again doesn't change itsthis. The firstbindwins.
function show() {
return this.label;
}
const first = show.bind({ label: 'first' });
const second = first.bind({ label: 'second' });
console.log(second()); // the first bind is permanent
console.log(first.name); // bound functions get a "bound " name prefix
Many APIs take a thisArg too: array.map(fn, thisArg), forEach, filter, some, every, find.
Arrow functions or bind are more common in practice.
Rule 4: new binding
Calling a function with new does four things:
- creates an empty object,
- links its prototype to the function's
prototypeproperty, - calls the function with
thisset to the new object, - returns the new object (unless the function returns a different object itself).
function User(name) {
this.name = name;
this.createdAt = 'today';
}
User.prototype.greet = function () {
return `Hi, I'm ${this.name}`;
};
const ann = new User('Ann');
console.log(ann.greet(), ann instanceof User);
// `new` beats bind: the bound `this` is ignored, the bound arguments are kept
const BoundUser = User.bind({ ignored: true }, 'Bob');
const bob = new BoundUser();
console.log(bob.name, bob instanceof User);
A class is the modern syntax for the same thing. Its constructor runs with this as the new instance,
and calling a class without new throws a TypeError.
Arrow functions: no this of their own
An arrow function doesn't get a this from its call. It uses the this of the surrounding code, exactly
like a closure uses an outer variable (it's fixed when the arrow function is created, and call, apply and
bind can't change it). That's what makes arrow functions the right tool inside methods:
class Poller {
constructor() {
this.ticks = 0;
}
startBroken() {
return [1, 2, 3].map(function () {
return this?.ticks; // a plain callback: `this` is undefined here
});
}
startFixed() {
return [1, 2, 3].map(() => ++this.ticks); // the arrow uses startFixed's `this`
}
}
const p = new Poller();
console.log(p.startBroken());
console.log(p.startFixed());
And it's what makes them the wrong tool as methods:
const counter = {
count: 0,
incrementArrow: () => {
// `this` comes from the code around the object literal, not from `counter`
return typeof this;
},
increment() {
return ++this.count;
},
};
console.log(counter.incrementArrow()); // module code: `this` is undefined
console.log(counter.increment());
An object literal doesn't create a scope for this. Only functions do. Use method shorthand
(increment() {}) for methods, and arrow functions for callbacks inside them.
this in classes
Class methods live on the prototype and follow the same rules as any function. A class body is
always strict, so a detached method gets undefined:
class SaveButton {
constructor(label) {
this.label = label;
}
onClick() {
return `saving from ${this.label}`;
}
}
const button = new SaveButton('toolbar');
const handler = button.onClick; // what addEventListener or a framework would store
try {
handler();
} catch (e) {
console.log(e.constructor.name, e.message);
}
There are three standard fixes, and you'll see all of them in real code:
class Fixed {
label = 'fixed';
// 1. class field holding an arrow function: `this` is captured per instance
onSave = () => `save ${this.label}`;
constructor() {
// 2. bind in the constructor: an own property that shadows the prototype method
this.onLoad = this.onLoad.bind(this);
}
onLoad() {
return `load ${this.label}`;
}
onDelete() {
return `delete ${this.label}`;
}
}
const f = new Fixed();
const handlers = [f.onSave, f.onLoad, () => f.onDelete()]; // 3. wrap the call in an arrow
console.log(handlers.map((h) => h()));
console.log('onSave on prototype?', 'onSave' in Fixed.prototype, '| own?', Object.hasOwn(f, 'onSave'));
The trade-offs:
- Arrow class fields are the most common fix in React and Angular code. But each instance gets its own
copy of the function, it's not on the prototype (so a subclass can't call
super.onSave(), and test spies on the prototype won't see it). bindin the constructor keeps the method on the prototype (sosupercalls work) and adds a bound copy per instance. It's verbose, which is why React class components used to be full of it.- An arrow at the call site (
onClick={() => this.save()}or.subscribe((x) => this.handle(x))) is explicit and needs no setup, but creates a new function each time that line runs.
Static methods follow the same rules: inside static create(), this is the class itself when
called as User.create(), so new this() builds the right subclass.
Method chaining: return this
A method that returns this can be followed by another method call on the same object. That's a
fluent API:
class QueryBuilder {
constructor() {
this.parts = [];
}
select(...fields) {
this.parts.push(`SELECT ${fields.join(', ')}`);
return this;
}
from(table) {
this.parts.push(`FROM ${table}`);
return this;
}
where(condition) {
this.parts.push(`WHERE ${condition}`);
return this;
}
toString() {
return this.parts.join(' ');
}
}
const sql = new QueryBuilder().select('id', 'name').from('users').where('active = 1');
console.log(String(sql));
jQuery, Knex, Mongoose queries and Express (app.use(...).get(...)) all chain this way. The catch: a mutable builder that returns this is shared. Branching from it
(const base = q.from('users'); const a = base.where(...)) changes base too. Immutable builders return a
new instance from every method instead, and RxJS pipe and Temporal dates work that way.
Gotchas people actually hit
- Parentheses don't lose
this, but expressions do.(obj.method)()still calls it onobj. But(0, obj.method)(),(cond ? obj.method : other)()and(obj.method = obj.method)()evaluate to the bare function first, sothisis lost. TypeScript and Babel emit(0, module.fn)()on purpose, so an imported function is never called with the module asthis. - Optional calls keep
this.obj.method?.()is a method call onobj. - Nested plain functions. Inside a method, a
function () {}callback has its ownthis(usuallyundefined). That's why old code wroteconst self = this;before every callback. Arrow functions replaced that. - Getters and setters get
thislike methods do, from the object you accessed them on. - Bound functions can't be unbound, and an arrow function's
thiscan't be changed at all. Calling.call(other)on either is silently ignored, so be careful with libraries that try to setthisfor you. thisat the top level of an ES module isundefined, and in a CommonJS file it'smodule.exports. UseglobalThiswhen you really want the global object.
Coming from C# or TypeScript
Side note
- In C#,
thisis fixed by the class, and a method group likebutton.Click += OnClickcreates a delegate that remembers its target. In JavaScript,button.addEventListener('click', this.onClick)passes only the function. You have to remember the target yourself, withbindor an arrow function. - TypeScript can catch some of this.
noImplicitThis(part ofstrict) flagsthiswith an unknown type, and you can declare what a function expects:function handler(this: HTMLButtonElement, e: Event). TypeScript still can't stop you from passingthis.onClickas a callback, which is why lint rules like@typescript-eslint/unbound-methodexist.
In real codebases
Side note
- React class components had to bind every handler (
this.handleClick = this.handleClick.bind(this)), then switched to arrow class fields. Function components and hooks don't usethisat all, which is one reason hooks took over. - Angular: passing a method as a callback (
.subscribe(this.onData),setTimeout(this.refresh),array.map(this.format)) loses the component. Write.subscribe((d) => this.onData(d)). - Node's
EventEmittercalls listeners withthisset to the emitter, unless the listener is an arrow function. DOMaddEventListenersetsthisto the element. jQuery callbacks get the DOM element. - Libraries that call your methods (Vue's Options API, Mongoose hooks, Mocha's
this.timeout()) depend on regular functions so they can setthis. Passing an arrow function there breaks them.
The exercises
- Fix the lost
this(easy): three real-looking classes with three classic bugs. - bindAll (easy): bind an object's methods so they survive being passed around.
- A fluent query builder (medium): chainable methods that return
this, then run the query. - An event emitter (medium): handlers called with the emitter as
this,once,offand chaining. - softBind (medium): a default
thisthat a method call orcallcan still override. - Implement bind (hard): partial arguments,
new,nameandlength, without the built-inbind. - autoBind (hard): bind every method along the prototype chain, like the
auto-bindpackage.
Practise this lesson
In the app: a short video, 7 exercises checked by real tests and a 12-question concept check. Free with a GitHub account.
Open in the app