Tutorials JavaScript this Keyword
Ch 37 / 78
Chapter 37 Intermediate 9 min read JavaScript

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.

What you'll learn
What this is and why it's dynamic
The 5 binding rules — default, implicit, explicit, new, arrow
Binding priority — which rule wins when multiple apply
call(), apply(), and bind() — explicit binding tools
Arrow functions — lexical this binding
Common this pitfalls and how to fix them

What 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.

JavaScript — this is dynamic
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)
Key rule
this is determined by the call site — not the definition site. The same function can have a different 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:

1
Default Binding
fn()
Standalone function call with no object. In sloppy mode, this = window. In strict mode, this = undefined.
2
Implicit Binding
obj.fn()
Function called as a method of an object. this = the object to the left of the dot at call time.
3
Explicit Binding
fn.call(obj)
Using call(), apply(), or bind() to directly specify the value of this.
4
new Binding
new Fn()
Calling a function with new. A brand new empty object is created, bound to this, and returned automatically.
5
Arrow Function (Lexical)
() => { }
Arrow functions don't have their own this. They inherit it from the enclosing lexical scope — fixed at definition time.
+
Event Listener
el.addEventListener
In DOM event handlers, 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:

1st Arrow (Lexical) () => { this } — inherited, cannot be overridden lexical scope
2nd new Binding new Fn() — fresh object, highest override power new object
3rd Explicit Binding fn.call(obj) / fn.bind(obj) — you choose specified obj
4th Implicit Binding obj.fn() — left of the dot obj
5th Default Binding fn() — fallback when no other rule applies global / undefined
JavaScript — All 5 Binding Rules
"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
JavaScript — call, apply, bind
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:

Regular function — own this
Own this binding — set at call time by the call site
Can be used as constructor — new Fn() works
this can be reassigned via call / apply / bind
Loses this when extracted from object (detached call)
Best for: object methods, constructors, class methods
Arrow function — lexical this
No own this — inherits from enclosing scope permanently
Cannot be used as constructor — new (() => {})() throws
call/apply/bind do not change this in an arrow function
this is fixed — always refers to the outer scope
Best for: callbacks, timers, event handlers inside methods
JavaScript — Arrow vs Regular this
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 ✗
Watch out
Never use arrow functions as object methods if you need 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:

Detached method call
Storing a method in a variable and calling it as a plain function — const fn = obj.method; fn(); — loses the implicit binding. Fix: use .bind(obj) or always call as obj.method().
Callback loses this
Passing an object method as a callback — setTimeout(obj.method, 100) — strips the object context. Fix: wrap in an arrow (setTimeout(() => obj.method(), 100)) or pre-bind (obj.method.bind(obj)).
Arrow function as object method
Defining a method with an arrow function — { greet: () => this.name } — makes this refer to the module/window scope, not the object. Fix: use shorthand method syntax.
class method as event handler
Adding a class method as an event listener — 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.
JavaScript — Pitfalls & Fixes
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;
};
}
⚡
Free Resource
Download our JavaScript Cheat Sheet
this binding rules, call/apply/bind & class patterns on one page.
Get Sheet

Try It — Live Editor

Experiment with this below. Try calling functions in different ways and observe how this changes with each call site.

Live Editor
✎ Editor
👁 Preview

Common Patterns & Recipes

Real-world patterns that use this correctly in modern JavaScript:

JavaScript — this Recipes
// ── 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)}`;
}
Quick Check
What does this refer to inside an arrow function?
Quick Check
Which method returns a new function with this permanently bound, without calling it immediately?
Chapter Summary
  • this is 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) or undefined (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. bind returns a new function; call/apply invoke 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 with call/apply/bind.
  • Never use arrow functions as object methods if you need this to 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

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel