The This Keyword
this is a special keyword that refers to the object a function is working on. Unlike most languages, where this always means the current instance, JavaScript decides this each time a function is called, based on how it was called. The same function can have different this values in different calls. Four rules (default, implicit, explicit and new binding) plus one exception (arrow functions) explain every case, and knowing them ends the most common source of JavaScript confusion.
In One Minute
- Implicit binding:
obj.method()setsthistoobj(the object before the dot). - Default binding: a plain call
fn()setsthistoundefinedin strict mode (modules, classes), or the global object in sloppy scripts. - Explicit binding:
fn.call(obj),fn.apply(obj)andfn.bind(obj)setthistoobj. newbinding:new Fn()setsthisto the newly created object.- Arrow functions have no
thisof their own: they use thethisof the surrounding code.
The Four Rules
| Rule | How the function is called | this is |
|---|---|---|
new binding | new Account() | The new object |
| Explicit binding | fn.call(obj), fn.apply(obj), fn.bind(obj)() | obj |
| Implicit binding | obj.fn() | obj |
| Default binding | fn() | undefined (strict) or globalThis (sloppy) |
When several could apply, the order of precedence is the order of the table: new beats explicit, which beats implicit, which beats default.
Implicit Binding: The Object Before the Dot
function describe() {
return `${this.name} owes $${this.balance}`;
}
const navika = { name: "Navika", balance: 120, describe };
const advitha = { name: "Advitha", balance: 45, describe };
console.log(navika.describe());
console.log(advitha.describe());
const school = { student: navika };
console.log(school.student.describe());Navika owes $120
Advitha owes $45
Navika owes $120Explanation: one function, three calls. In each, this is the object immediately before the final dot: navika, advitha, and in school.student.describe(), school.student, which is navika. Where the function was defined doesn't matter at all.
Default Binding: A Plain Call
When a function is called without an object (no dot, no call, no new), there is nothing to bind this to:
function sloppyThis() {
return this === globalThis;
}
function strictThis() {
"use strict";
return this;
}
console.log(sloppyThis());
console.log(strictThis());true
undefinedIn strict mode (which includes all ES modules and class bodies), this is undefined. In older non-strict scripts, it falls back to the global object, which is how code accidentally created global variables. Modern code should treat this in a plain call as undefined.
The Lost this Bug
Implicit binding happens only at the moment of the call obj.method(). Taking the method off the object, by storing it in a variable or passing it as a callback, loses the binding:
"use strict";
const account = {
owner: "Srihitha",
describe() {
return `Owner: ${this.owner}`;
},
};
const detached = account.describe;
try {
detached();
} catch (err) {
console.log(err.name + ": " + err.message);
}
function runLater(callback) {
return callback();
}
try {
runLater(account.describe);
} catch (err) {
console.log("as a callback:", err.name);
}TypeError: Cannot read properties of undefined (reading 'owner')
as a callback: TypeErroraccount.describe (without parentheses) is just the function. When it is called later as callback(), it's a plain call, so this is undefined. This happens with timers, event listeners, promise callbacks, array methods and React event props.
Three Fixes
const account = {
owner: "Srihitha",
describe() {
return `Owner: ${this.owner}`;
},
};
const runLater = (callback) => callback();
console.log(runLater(() => account.describe()));
console.log(runLater(account.describe.bind(account)));
class Account {
owner = "Advitha";
describe = () => `Owner: ${this.owner}`;
}
console.log(runLater(new Account().describe));Owner: Srihitha
Owner: Srihitha
Owner: Advitha| Fix | How | Trade-off |
|---|---|---|
| Wrap in an arrow | () => obj.method() | Clear; a new function each time |
bind | obj.method.bind(obj) | Permanent this; keep the bound function if you need to remove a listener |
| Arrow-function class field | method = () => { ... } | Bound per instance automatically; uses memory per instance, not shared on the prototype |
Explicit Binding: call, apply and bind
These three methods, available on every function, set this explicitly. They have their own lesson next; in short:
function describe(prefix, suffix) {
return `${prefix}${this.name} owes $${this.balance}${suffix}`;
}
const student = { name: "Advitha", balance: 45 };
console.log(describe.call(student, "Note: ", "."));
console.log(describe.apply(student, ["Note: ", "!"]));
const bound = describe.bind(student, "Reminder: ");
console.log(bound("?"));Note: Advitha owes $45.
Note: Advitha owes $45!
Reminder: Advitha owes $45?call and apply call the function immediately (arguments listed, or as an array); bind returns a new function with this (and optionally some arguments) fixed.
new Binding
When a function is called with new, JavaScript creates a new object and sets this to it:
function Payment(name, amount) {
this.name = name;
this.amount = amount;
}
const p = new Payment("Navika", 120);
console.log(p.name, p.amount, p instanceof Payment);
const bound = Payment.bind({ ignored: true });
const q = new bound("Srihitha", 85);
console.log(q.name, "ignored" in q);Navika 120 true
Srihitha falseThe second example shows precedence: new beats bind. Even a bound function gets the brand new object as this when called with new.
Arrow Functions: No Own this
Arrow functions don't have their own this. Inside an arrow, this is whatever it was in the surrounding scope at the place the arrow was written (lexical this). None of the four rules applies to arrows, and call, apply and bind can't change it:
const tracker = {
owner: "Navika",
amounts: [120, 60],
labels() {
return this.amounts.map((a) => `${this.owner}: ${a}`);
},
broken() {
return this.amounts.map(function (a) {
return `${this?.owner}: ${a}`;
});
},
};
console.log(tracker.labels());
console.log(tracker.broken());
const arrow = () => this === globalThis;
console.log(arrow.call({ x: 1 }));['Navika: 120', 'Navika: 60']
['undefined: 120', 'undefined: 60']
trueExplanation: inside labels, the arrow callback uses the method's this, which is tracker. In broken, the regular function callback is called by map as a plain function, so it gets its own, default this. The last line shows that call can't override an arrow's this: the arrow keeps the this of the code around it (here the top level of a non-module script, where this is the global object), even though call passed a different object.
| Regular function | Arrow function | |
|---|---|---|
this decided by | How it's called | Where it's written |
call/apply/bind change this | Yes | No |
| Use as an object method | Yes | No (no access to the object) |
| Use as a callback inside a method | Loses this | Keeps the method's this |
this in Classes and Event Handlers
Classes are always strict, and their methods follow the same rules: instance.method() binds the instance; a detached method gets undefined.
Event listeners added with addEventListener and a regular function get this set to the element the listener is attached to (the same as event.currentTarget). With an arrow function, they don't:
<button id="pay">Pay</button>
<script>
const button = document.querySelector("#pay");
button.addEventListener("click", function (event) {
console.log("regular:", this.id, this === event.currentTarget);
});
button.addEventListener("click", (event) => {
console.log("arrow:", this === undefined || this === window, event.currentTarget.id);
});
</script>regular: pay true
arrow: true payIn Practice
The Fee Tracker's Reminder class schedules a reminder with a timer. Passing the method directly would lose this; an arrow wrapper keeps it:
class Reminder {
constructor(student) {
this.student = student;
this.sent = 0;
}
send() {
this.sent++;
console.log(`Reminder ${this.sent} sent to ${this.student}`);
}
schedule(ms) {
setTimeout(() => this.send(), ms);
}
}
const r = new Reminder("Advitha");
r.schedule(10);
r.schedule(20);Reminder 1 sent to Advitha
Reminder 2 sent to AdvithaInside schedule, this is the instance (r.schedule(...)), and the arrow passed to setTimeout keeps it, so this.send() works when the timer fires.
Common Mistakes
Passing obj.method as a callback. this is lost. Wrap it: () => obj.method(), or bind.
Using an arrow function as an object method. It can't see the object. Use method shorthand.
Expecting bind to work on an arrow. It doesn't change an arrow's this.
Assuming this means the same thing everywhere in a file. It depends on each call.
Under the Hood
When a function is called, the engine computes a this value as part of creating the call's execution context. For a property reference call like obj.method(), the specification's call evaluation records the base object (obj) of the reference and passes it as this. For a plain identifier call, there is no base object, so undefined is passed; non-strict functions then replace undefined (and null) with the global object, and wrap primitives in objects ("text".method() in sloppy mode gets a String object). call and apply pass their first argument directly as the this value. bind creates a bound function exotic object that remembers a target function, a bound this and bound arguments, and always calls the target with them, except under new, which ignores the bound this. Arrow functions are created with a flag that makes them lexical-this functions: they skip the this binding step entirely, so this inside them resolves through the scope chain like an ordinary variable, finding the nearest enclosing non-arrow function's this.
Interview Corner
How is this determined in JavaScript?
At call time, by how the function is invoked: with new, this is the new object; with call, apply or a bound function, it's the provided value; as obj.method(), it's obj; as a plain call, it's undefined in strict mode or the global object otherwise. Arrow functions don't bind this; they use the enclosing scope's this. Precedence: new, explicit, implicit, default.
Why does a method lose this when passed as a callback?
Implicit binding comes from the obj. in the call expression. Passing obj.method passes only the function value; the receiver later calls it as a plain function, so default binding applies. Fix with an arrow wrapper, bind, or an arrow-function class field.
What does this print?
Show solution
"use strict";
const obj = {
value: 42,
regular() { return this?.value; },
arrow: () => typeof this,
nested() { return [1].map(() => this.value)[0]; },
};
const { regular } = obj;
console.log(obj.regular(), regular(), obj.arrow(), obj.nested());42 undefined undefined 42obj.regular() binds obj. The destructured regular() is a plain call in strict mode. The arrow at object-literal level uses the surrounding this (here undefined). nested's arrow uses nested's this, which is obj.
Practice
Challenge: Fix the code below so that clicking (simulated by calling handler()) logs Saved by Navika, without changing the save method.
const user = {
name: "Navika",
save() { return `Saved by ${this.name}`; },
};
const handler = user.save;
console.log(handler());Show solution
"use strict";
const user = {
name: "Navika",
save() { return `Saved by ${this.name}`; },
};
const handler = user.save.bind(user);
console.log(handler());Saved by NavikaKey Takeaways
| Call | this |
|---|---|
new Fn() | The new object |
fn.call(obj) | obj |
obj.fn() | obj |
fn() (strict) | undefined |
| Arrow function | Surrounding scope's this |
Was this tutorial helpful?