Explain it simply
Explain it simply
Think about the word "I". When Aung Kyaw says "I am hungry", I means Aung Kyaw; when Ma Ma says the very same sentence, I means Ma Ma. The sentence does not change, but who says it decides what it means.
JavaScript's this works the same way. this.name inside a function means "my name", and who "I" am is settled at the moment the function is called. Call person.greet() and I is person; call plain greet() with no object in front and there is no "I" at all.
Problem → Why → Solution
The problem: passed as a callback, a method forgets its object
Calling counter.increment() directly works fine. But hand it to setTimeout(counter.increment, 1000) so it runs a second later, and it logs NaN instead of 2, while counter.count stays stuck at 1. No error is thrown. The function is identical; only the way it gets called has changed.
const counter = {
count: 0,
increment() {
this.count++;
console.log(this.count);
},
};
counter.increment(); // 1
setTimeout(counter.increment, 1000); // NaN, and counter.count is still 1Why does this happen?
Writing counter.increment detaches the function from its object and hands over only the function, not counter. When the time comes, setTimeout calls it on its own terms: browsers pass window as this, and Node.js passes its internal Timeout object. Either way this is not counter, so this.count is undefined and ++ turns it into NaN. The fixes are bind(counter) or () => counter.increment().
Core concept: the call site decides this
The place where a function is called, and the way it is called, is the call site. To work out this, ignore the function body and look at the line that calls it. Regular functions, meaning those written with the function keyword or as method shorthand, follow four rules.
| How it is called | What this is |
|---|---|
| new Fn() | The newly created object |
| fn.call(obj) / fn.apply(obj) / fn.bind(obj)() | The obj you passed explicitly |
| obj.method() | The obj before the dot |
| fn() with nothing in front | Strict mode: undefined; sloppy script: the global object |
When more than one rule seems to apply, the one higher in the table wins: a bound function called as obj.method() still uses the object given to bind. Class bodies and ES modules are strict, so a plain call gets this as undefined, and reading this.something throws a TypeError. That is actually helpful, because the mistake surfaces immediately.
Arrow functions ignore all of these rules. An arrow has no this of its own; it uses the this of the surrounding code where it was written, its lexical scope, and call or bind cannot change it. That makes arrows perfect for a setTimeout or forEach callback inside a method, and wrong for the method itself, because an arrow method's this will not point at the object.
Reading this at the top level, outside any function, also depends on the environment: window in a browser classic script, undefined in an ES module, and module.exports in a Node.js CommonJS file. Because of these differences, never write code that relies on top-level this. When you genuinely need the global object, use globalThis, which works everywhere.
- Arrow? Use the outer this
- Called with new? The new object
- call/apply/bind? The given object
- obj.fn()? The obj left of the dot
- Nothing? undefined in strict mode
Do not stare at the function body; look at the calling line, just left of the dot.
General pattern
obj.method(); // this = obj
const fn = obj.method; fn(); // this = undefined (strict)
fn.call(other, arg1, arg2); // this = other, args listed
fn.apply(other, [arg1, arg2]); // this = other, args in an array
const bound = fn.bind(other); // new function, this fixed to other
new Constructor(); // this = the new object
const arrow = () => this; // this = the surrounding thiscall and apply invoke the function immediately and differ only in how arguments are passed. bind does not call anything; it returns a new function with this locked in.
Example: this in five situations
This example shows five ways this gets its value, each called once. "use strict" makes it behave the same in a browser and in Node: the detached call throws, and try...catch catches it. The setTimeout callback prints "Arrow: 42" last because it runs only after all synchronous code has finished, so predict the order of the output before you run it.
"use strict";
// 1. Method call: this is the object before the dot
const person = {
name: "Aung Kyaw",
greet() {
return `Hello from ${this.name}`;
},
};
console.log(person.greet());
// 2. Detached call: nothing before the dot, so this is undefined
const greet = person.greet;
try {
greet();
} catch (error) {
console.log(`Detached: ${error.constructor.name}`);
}
// 3. bind returns a copy with this fixed
const boundGreet = person.greet.bind(person);
console.log(boundGreet());
// 4. Explicit binding with call
function introduce(greeting) {
return `${greeting}, I am ${this.name}`;
}
const user = { name: "Ma Ma" };
console.log(introduce.call(user, "Hi"));
// 5. An arrow callback keeps the method's this
const timer = {
value: 42,
start() {
setTimeout(() => {
console.log(`Arrow: ${this.value}`);
}, 10);
},
};
timer.start();Code breakdown
- Line 10
console.log(person.greet());person sits before the dot, so this inside greet is person and the result is "Hello from Aung Kyaw".
- Lines 13-15
const greet = person.greet;Copying the function into a variable cuts its tie to person. Calling greet() with no object makes this undefined in strict mode, and this.name throws a TypeError.
- Line 21
const boundGreet = person.greet.bind(person);bind returns a new function permanently tied to person, so boundGreet() sees person however it is called.
- Line 29
console.log(introduce.call(user, "Hi"));call's first argument, user, becomes this, and "Hi" fills the greeting parameter. introduce belongs to no object, yet call lets you borrow it for any object.
- Lines 35-37
setTimeout(() => {The arrow has no this of its own, so it uses start()'s this, which is timer. A function () {...} here would be called by setTimeout in its own way, and this would no longer be timer.
Hello from Aung Kyaw
Detached: TypeError
Hello from Aung Kyaw
Hi, I am Ma Ma
Arrow: 42call, apply and bind compared
| Method | Calls right away? | How arguments are passed |
|---|---|---|
| fn.call(obj, a, b) | Yes | One by one, separated by commas |
| fn.apply(obj, [a, b]) | Yes | Inside a single array |
| fn.bind(obj, a) | No, returns a new function | Can be pre-filled (partial application) |
Since spread syntax arrived (fn.call(obj, ...args)), apply is needed far less often. Binding an already bound function changes nothing: the first bind wins and this can never be re-targeted. In the browser, a function () {...} passed to addEventListener gets the element as this, while an arrow keeps the outer this instead; in that case read event.currentTarget.
In real projects
Where this shows up in real projects
The lost-this bug turns up most often in event handlers and timers. Write button.addEventListener("click", this.save) inside a class and, when save() runs, this is the button element rather than your instance, so this.data is undefined. There are three common fixes: this.save = this.save.bind(this) in the constructor, an () => this.save() wrapper, or writing the method as an arrow class field, save = () => {...}.
An arrow class field creates a separate function copy for every instance, which costs more memory than a prototype method when there are thousands of instances, so reserve it for methods you really pass around as callbacks. When React was written with class components, binding handlers in the constructor was the standard pattern; modern function components avoid this entirely.
Common mistakes
Common mistakes
1. Writing an object method as an arrow function
In const shop = { name: "Mya", show: () => this.name };, the arrow takes the this of the code around the object literal, such as the module's top level. An object literal's braces do not create a new scope, so this is not shop; in a module it is undefined and the call throws a TypeError. Write methods as shorthand: show() { return this.name; }.
2. A nested regular function inside a method
In printAll() { this.items.forEach(function (item) { console.log(this.prefix + item); }); }, the forEach callback is a plain function call, so its this is not printAll's this. In strict mode it is undefined and this.prefix throws a TypeError. Switching the callback to an arrow, (item) => ..., borrows the outer this and solves it.
3. Pulling a method out with destructuring
const { greet } = person; greet(); is the same as const greet = person.greet: the tie to the object is cut. It looks tidy, which is why this bug sneaks in unnoticed. If a method uses this, call it as person.greet(), or bind it before pulling it out.
Mini challenge
Mini challenge: rescue a lost this three ways
Show this getting lost when counter.increment is passed as a callback, then fix it with bind, with an arrow wrapper, and with call.
- increment() adds 1 to this.count and returns "<label>: <count>"
- Pass counter.increment straight to runLater and print the error's constructor name
- Fix it once with bind and once with an arrow wrapper, printing each result
- Use call to run increment on { label: "likes", count: 10 }, then print both counts
"use strict";
const counter = {
label: "clicks",
count: 0,
increment() {
// TODO: add 1 to this object's count and return "<label>: <count>"
},
};
function runLater(callback) {
return callback();
}
// TODO 1: pass counter.increment directly to runLater inside try/catch
// and print the caught error's constructor name
// TODO 2: fix it with bind
// TODO 3: fix it with an arrow function wrapper
// TODO 4: use call to run increment on { label: "likes", count: 10 },
// then print counter.count and the other object's countExpected: The console prints five lines: Lost this: TypeError clicks: 1 clicks: 2 likes: 11 2 11
Show hint
runLater calls callback() with no object in front, which is where this gets lost. Passing counter.increment.bind(counter) or () => counter.increment() restores counter. call lets you borrow the method for a different object.
Show solution
"use strict";
const counter = {
label: "clicks",
count: 0,
increment() {
this.count += 1;
return `${this.label}: ${this.count}`;
},
};
function runLater(callback) {
return callback(); // no object in front of the call
}
// 1. Passing the method alone loses this
try {
runLater(counter.increment);
} catch (error) {
console.log(`Lost this: ${error.constructor.name}`);
}
// 2. Fix with bind
console.log(runLater(counter.increment.bind(counter)));
// 3. Fix with an arrow wrapper
console.log(runLater(() => counter.increment()));
// 4. Borrow the method for another object with call
const likes = { label: "likes", count: 10 };
console.log(counter.increment.call(likes));
console.log(counter.count, likes.count);Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- this is decided by how a function is called (the call site), not where it was written.
- obj.method() gives this = obj; a plain call with no object gives undefined in strict mode.
- call and apply set this and invoke at once; bind returns a new function with this locked in.
- Arrow functions borrow the outer this: great for callbacks inside methods, wrong for the methods themselves.
MDN — Using Classes — MDN Web Docs