this Keyword
this is one of JavaScript's
most misunderstood features. Unlike most languages where
this refers to the enclosing class,
in JavaScript its value is determined entirely by how a function is
called — not where it is defined. Master the 5 binding rules and
you'll never be confused by this again.
this is and why it's dynamic
this binding
this pitfalls and how to fix
themWhat is this?
this is a special keyword
that refers to the execution context — the object that "owns"
the currently running function. Its value is not set at
function definition time; it is set at call time, making it
completely dynamic.
There is one simple rule for understanding
this: look at where the function is
called, not where it is defined. More specifically, look at
what is to the left of the dot when the function is invoked.
function greet() {
console.log(`Hello, I am ${this.name}`);
}
const alice = { name: "Alice", greet };
const bob = { name: "Bob", greet };
alice.greet(); // "Hello, I am Alice" — this = alice
bob.greet(); // "Hello, I am Bob" — this = bob
// Same function, different this — determined by call site!
const fn = alice.greet;
fn(); // "Hello, I am undefined" — no object, this = global (or undefined in strict)
this value each time it is
called, depending on how and where it is invoked.
The 5 Binding Rules
There are exactly 5 rules that determine
what this refers to in any given call.
They are checked in order of priority — the highest-priority rule that
applies wins:
this = window. In strict mode, this =
undefined.
this = the
object to the left of the dot at call time.call(), apply(), or
bind() to directly specify the value of this.
new. A brand new empty object
is created, bound to this, and returned automatically.this. They
inherit it from the enclosing lexical scope — fixed at definition time.
this refers to the
element that fired the event — unless an arrow function is used.
Binding Priority
When more than one binding rule could apply, the higher-priority rule wins. The order from highest to lowest:
"use strict";
// ── 1. Default binding ───────────────────────────────────────
function showThis() { console.log(this); }
showThis(); // undefined (strict) | window (sloppy)
// ── 2. Implicit binding ──────────────────────────────────────
const obj = {
name: "Priya",
greet() { console.log(this.name); }
};
obj.greet(); // "Priya" — this = obj
// ── 3. Explicit binding ──────────────────────────────────────
function introduce() { return `I am ${this.name}`; }
const user = { name: "Rahul" };
introduce.call(user); // "I am Rahul"
introduce.apply(user); // "I am Rahul"
const bound = introduce.bind(user);
bound(); // "I am Rahul"
// ── 4. new binding ───────────────────────────────────────────
function Person(name) {
this.name = name; // this = brand new object
}
const p = new Person("Alice");
console.log(p.name); // "Alice"
// ── 5. Arrow function (lexical) ──────────────────────────────
const timer = {
id: 42,
start() {
setTimeout(() => {
console.log(this.id); // ✅ 42 — arrow inherits this from start()
}, 1000);
}
};
timer.start();call(), apply(), and bind()
These three methods live on Function.prototype
and let you explicitly set the value of
this when calling a function:
| Method | Invokes immediately? | Arguments style | Returns |
|---|---|---|---|
| .call(thisArg, a, b, …) | Yes — right now | Comma-separated list | Function return value |
| .apply(thisArg, [a, b, …]) | Yes — right now | Single array of args | Function return value |
| .bind(thisArg, a?, b?, …) | No — returns new function | Comma-separated (pre-set) | New bound function |
function fullName(greeting, punctuation) {
return `${greeting}, ${this.first} ${this.last}${punctuation}`;
}
const person = { first: "Priya", last: "Sharma" };
// call — args as comma-separated list
fullName.call(person, "Hello", "!"); // "Hello, Priya Sharma!"
// apply — args as array (great when you already have an array)
fullName.apply(person, ["Hi", "."]); // "Hi, Priya Sharma."
// bind — returns a new permanently bound function
const greetPriya = fullName.bind(person, "Hey");
greetPriya("?"); // "Hey, Priya Sharma?"
greetPriya("!"); // "Hey, Priya Sharma!" — this stays bound
// Practical — borrow a method from another object
const nums = [5, 2, 8, 1];
const max = Math.max.apply(null, nums); // 8
const max2 = Math.max(...nums); // 8 (modern spread)
// bind in event handlers — fix lost this
class Button {
constructor() {
this.count = 0;
this.handleClick = this.handleClick.bind(this); // ← fix
}
handleClick() { this.count++; }
}Arrow Functions vs Regular Functions
The biggest source of this
confusion in modern JavaScript is mixing arrow and regular functions.
The key difference: regular functions get their own
this at call time, arrow functions inherit
this from the surrounding scope at definition time:
this binding — set at call
time by the call site
new Fn() works
this can be reassigned via call /
apply / bind
this when extracted from
object (detached call)
this — inherits from
enclosing scope permanently
new (() => {})() throws
call/apply/bind do not change
this in an arrow function
this is fixed — always refers to
the outer scope
const obj = {
name: "Counter",
count: 0,
// ── Regular function — this lost in setTimeout ───────────────
startBroken() {
setTimeout(function() {
this.count++; // ❌ this = window/undefined — NOT obj!
console.log(this.count); // NaN or error
}, 100);
},
// ── Arrow function — lexically inherits this from startFixed ─
startFixed() {
setTimeout(() => {
this.count++; // ✅ this = obj — inherited from startFixed's this
console.log(this.count); // 1
}, 100);
},
// ── Arrow as object METHOD — wrong! loses implicit binding ───
brokenMethod: () => {
console.log(this.name); // ❌ this = outer scope (not obj)
}
};
obj.startFixed(); // 1 ✓
obj.brokenMethod(); // undefined ✗this to refer to the object. Arrow functions inherit
this from the outer scope (often the module or
window), not from the object. Use regular functions or
shorthand method syntax (greet() { }) for object methods.
Common this Pitfalls & Fixes
These are the scenarios where
this behaves unexpectedly — and the
modern fixes for each:
const fn = obj.method; fn(); — loses the implicit binding. Fix:
use .bind(obj) or always call as obj.method().setTimeout(obj.method, 100) — strips the object context. Fix: wrap in an
arrow (setTimeout(() => obj.method(), 100)) or pre-bind
(obj.method.bind(obj)).
{ greet: () => this.name } — makes this refer to the
module/window scope, not the object. Fix: use shorthand method syntax.
btn.addEventListener('click', this.handleClick) — makes this
become the button element. Fix:
this.handleClick = this.handleClick.bind(this) in the constructor, or use
an arrow class field.
const counter = {
value: 10,
increment() { return ++this.value; }
};
// ── Pitfall 1: detached method call ──────────────────────────
const inc = counter.increment; // strips the object
// inc(); ❌ TypeError in strict mode
// Fix A: bind
const incBound = counter.increment.bind(counter);
incBound(); // ✅ 11
// Fix B: always call on the object
counter.increment(); // ✅ 12
// ── Pitfall 2: callback loses this ───────────────────────────
const obj = {
name: "App",
init() {
// ❌ wrong — this becomes window/undefined
// setTimeout(this.run, 100);
// ✅ Fix 1: arrow wrapper
setTimeout(() => this.run(), 100);
// ✅ Fix 2: bind
setTimeout(this.run.bind(this), 200);
},
run() { console.log(`${this.name} running`); }
};
// ── Pitfall 3: class method + event handler ───────────────────
class Toggle {
constructor(el) {
this.on = false;
// ❌ this inside handleClick will be the button element
// el.addEventListener("click", this.handleClick);
// ✅ Fix: pre-bind in constructor
el.addEventListener("click", this.handleClick.bind(this));
}
handleClick() { this.on = !this.on; console.log(this.on); }
}
// ✅ Modern fix: arrow class field (no bind needed)
class Toggle2 {
on = false;
handleClick = () => { // arrow field — lexically binds this
this.on = !this.on;
};
}Try It — Live Editor
Experiment with this below.
Try calling functions in different ways and observe how
this changes with each call site.
Common Patterns & Recipes
Real-world patterns that use
this correctly in modern JavaScript:
// ── Method chaining with this ────────────────────────────────
class QueryBuilder {
constructor() { this._table = ""; this._where = ""; this._limit = 0; }
from(table) { this._table = table; return this; } // ← return this enables chaining
where(cond) { this._where = cond; return this; }
limit(n) { this._limit = n; return this; }
build() { return `SELECT * FROM ${this._table} WHERE ${this._where} LIMIT ${this._limit}`; }
}
const q = new QueryBuilder()
.from("users")
.where("active = 1")
.limit(10)
.build();
// "SELECT * FROM users WHERE active = 1 LIMIT 10"
// ── Arrow class field — no bind needed ───────────────────────
class Timer {
count = 0;
tick = () => { // arrow field — this is always the class instance
this.count++;
console.log(this.count);
};
start() { setInterval(this.tick, 1000); } // no .bind() needed!
}
// ── Mixin — borrow methods via call ───────────────────────────
function serialize() { return JSON.stringify(this); }
const config = { host: "localhost", port: 3000 };
const profile = { name: "Alice", role: "admin" };
serialize.call(config); // '{"host":"localhost","port":3000}'
serialize.call(profile); // '{"name":"Alice","role":"admin"}'
// ── Determine this value safely ──────────────────────────────
function whoAmI() {
if (this === undefined) return "strict: this is undefined";
if (this === globalThis) return "sloppy: this is global";
return `this is: ${JSON.stringify(this)}`;
}this refer to inside an arrow
function?this
permanently bound, without calling it immediately?thisis dynamic — its value is determined at call time by how the function is invoked, not where it is defined.- Default binding — plain call
fn():this=window(sloppy) orundefined(strict mode). - Implicit binding — method call
obj.fn():this= the object to the left of the dot. - Explicit binding —
fn.call(obj),fn.apply(obj),fn.bind(obj):this= specified object.bindreturns a new function;call/applyinvoke immediately. - new binding —
new Fn():this= a brand-new object created for that call. - Arrow functions have no own
this— they inherit it from the enclosing lexical scope and it cannot be overridden withcall/apply/bind. - Never use arrow functions as object methods if you need
thisto refer to the object. - Modern fix for class event handlers: arrow class fields
(
handleClick = () => {}) avoid the need for.bind(this)in the constructor.
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.