惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

N
Netflix TechBlog - Medium
S
Secure Thoughts
aimingoo的专栏
aimingoo的专栏
量子位
F
Full Disclosure
云风的 BLOG
云风的 BLOG
D
Docker
Stack Overflow Blog
Stack Overflow Blog
Last Week in AI
Last Week in AI
Security Latest
Security Latest
Project Zero
Project Zero
Cyberwarzone
Cyberwarzone
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
AWS News Blog
AWS News Blog
G
GRAHAM CLULEY
T
Threat Research - Cisco Blogs
The Hacker News
The Hacker News
The Register - Security
The Register - Security
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
MyScale Blog
MyScale Blog
博客园_首页
阮一峰的网络日志
阮一峰的网络日志
P
Privacy & Cybersecurity Law Blog
V
Visual Studio Blog
A
Arctic Wolf
L
LINUX DO - 热门话题
W
WeLiveSecurity
Google DeepMind News
Google DeepMind News
TaoSecurity Blog
TaoSecurity Blog
Recorded Future
Recorded Future
K
Kaspersky official blog
L
Lohrmann on Cybersecurity
V
V2EX
Recent Announcements
Recent Announcements
N
News and Events Feed by Topic
MongoDB | Blog
MongoDB | Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
S
Securelist
S
Security Affairs
Forbes - Security
Forbes - Security
P
Proofpoint News Feed
Google DeepMind News
Google DeepMind News
C
Cisco Blogs
AI
AI
Vercel News
Vercel News
博客园 - 三生石上(FineUI控件)
Cisco Talos Blog
Cisco Talos Blog
T
Tor Project blog
Scott Helme
Scott Helme
Spread Privacy
Spread Privacy

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Understanding the `this` Keyword in JavaScript
Pratham · 2026-05-10 · via DEV Community

The most confusing word in JavaScript — explained by asking one simple question.


If there's one concept that made me stare at my screen in genuine confusion, it's this. Not because the idea is complicated, but because this changes its meaning depending on where and how you use it. The same keyword can refer to completely different things in different situations.

I'd write this.name inside a function and get undefined. Then I'd write the exact same thing inside an object method and get the correct value. Why? What changed? Is JavaScript just messing with me?

Turns out, no. There's a clear rule. And once I learned it in the ChaiCode Web Dev Cohort 2026, this stopped being scary and started making complete sense. Let me share that mental model with you.


What Does this Represent?

Here's the one-line explanation that makes everything click:

this refers to the object that is calling the function.

That's it. Not where the function was written. Not where it was defined. But who is calling it at the moment of execution.

Think of it like the word "I" in English. When I say "I am Pratham," the word "I" refers to me. When you say "I am [your name]," the same word "I" refers to you. The word doesn't change — the speaker changes.

this works the same way. It's a pronoun for the caller.

"Who is calling this function right now?"

The answer to that question IS the value of `this`.

Enter fullscreen mode Exit fullscreen mode


this in the Global Context

When you use this outside any function or object — just floating in the global scope — it refers to the global object.

In the Browser

console.log(this); // Window object
console.log(this === window); // true

Enter fullscreen mode Exit fullscreen mode

In Node.js

console.log(this); // {} (module's exports object in Node)

Enter fullscreen mode Exit fullscreen mode

Global Variables and this

var name = "Pratham"; // var attaches to the global object

console.log(this.name); // "Pratham" (in browser)
console.log(window.name); // "Pratham" (same thing)

Enter fullscreen mode Exit fullscreen mode

Note: let and const do not attach to the global object. Only var does.

let age = 22;
console.log(this.age); // undefined — let doesn't attach to window

Enter fullscreen mode Exit fullscreen mode

In practice, you'll rarely use this in the global context deliberately. It's mostly important for understanding why things behave unexpectedly.


this Inside Objects — Where It Makes the Most Sense

This is where this is the most intuitive. When a function is called as a method of an object, this refers to that object.

const user = {
  name: "Pratham",
  age: 22,
  greet() {
    console.log(`Hi, I'm ${this.name} and I'm ${this.age} years old.`);
  },
};

user.greet(); // "Hi, I'm Pratham and I'm 22 years old."

Enter fullscreen mode Exit fullscreen mode

Who is calling greet()?user is. So this = user.

That means this.name is user.name"Pratham", and this.age is user.age22.

Another Example

const car = {
  brand: "Toyota",
  model: "Camry",
  year: 2024,
  describe() {
    return `${this.year} ${this.brand} ${this.model}`;
  },
};

console.log(car.describe()); // "2024 Toyota Camry"

Enter fullscreen mode Exit fullscreen mode

Who called describe()?car did. So this = car.

Multiple Objects, Same Function

Here's where it gets interesting — the same function can be used by different objects, and this changes accordingly:

function introduce() {
  console.log(`I'm ${this.name} from ${this.city}`);
}

const person1 = { name: "Pratham", city: "Delhi", introduce };
const person2 = { name: "Arjun", city: "Mumbai", introduce };

person1.introduce(); // "I'm Pratham from Delhi"
person2.introduce(); // "I'm Arjun from Mumbai"

Enter fullscreen mode Exit fullscreen mode

Same function. Different callers. Different this.

Visual: Caller → Function Relationship

person1.introduce()
   ↑         ↑
 caller    method
   │
   └──→ this = person1
         └──→ this.name = "Pratham"
         └──→ this.city = "Delhi"

person2.introduce()
   ↑         ↑
 caller    method
   │
   └──→ this = person2
         └──→ this.name = "Arjun"
         └──→ this.city = "Mumbai"

Enter fullscreen mode Exit fullscreen mode


this Inside Regular Functions

Here's where things get confusing — and where most beginners trip up.

When a regular function is called on its own (not as a method of an object), this defaults to the global object in non-strict mode, or undefined in strict mode.

Non-Strict Mode

function showThis() {
  console.log(this);
}

showThis(); // Window (in browser) — no one is calling it, so this = global

Enter fullscreen mode Exit fullscreen mode

Who is calling showThis()? → Nobody specific. There's no object.showThis(). So this falls back to the global object.

Strict Mode

"use strict";

function showThis() {
  console.log(this);
}

showThis(); // undefined — strict mode doesn't default to global

Enter fullscreen mode Exit fullscreen mode

Strict mode is more honest about it: if no one is explicitly calling the function, this is undefined instead of silently becoming the global object.

The Classic Gotcha: Nested Functions

const user = {
  name: "Pratham",
  greet() {
    console.log(`Hello, ${this.name}`); // ✅ Works — this = user

    function inner() {
      console.log(`Inner: ${this.name}`); // ❌ undefined!
    }
    inner();
  },
};

user.greet();
// "Hello, Pratham"
// "Inner: undefined"

Enter fullscreen mode Exit fullscreen mode

Wait, what? inner() is called inside a method of user, so why isn't this still user?

Because inner() is called as a standalone function, not as user.inner(). There's no object before the dot. So this defaults to the global object (or undefined in strict mode), where name doesn't exist.

The Fix: Arrow Functions or that/self

Arrow function fix (modern, preferred):

const user = {
  name: "Pratham",
  greet() {
    const inner = () => {
      console.log(`Inner: ${this.name}`); // ✅ "Pratham"
    };
    inner();
  },
};

user.greet(); // "Inner: Pratham"

Enter fullscreen mode Exit fullscreen mode

Arrow functions don't have their own this. They inherit this from the surrounding scope — which in this case is greet(), where this is user. Problem solved.

that/self fix (older pattern, still common):

const user = {
  name: "Pratham",
  greet() {
    const that = this; // Save the reference

    function inner() {
      console.log(`Inner: ${that.name}`); // ✅ "Pratham"
    }
    inner();
  },
};

user.greet(); // "Inner: Pratham"

Enter fullscreen mode Exit fullscreen mode

You save this into a regular variable (that or self) before the inner function, so it's accessible via normal closure rules.


How Calling Context Changes this

This is the key insight: this is NOT determined by where a function is written. It's determined by HOW the function is called.

Let me prove it:

const user = {
  name: "Pratham",
  greet() {
    console.log(`Hi, I'm ${this.name}`);
  },
};

// Called as a method — this = user
user.greet(); // "Hi, I'm Pratham" ✅

// Extracted into a variable — context is lost
const greetFn = user.greet;
greetFn(); // "Hi, I'm undefined" ❌ (or error in strict mode)

Enter fullscreen mode Exit fullscreen mode

When we assign user.greet to greetFn, we're taking the function out of the object. Now greetFn() is called without any object in front of it. No caller → this falls back to global → this.name is undefined.

The Different Calling Contexts — A Summary

┌─────────────────────────────────────────────────────────────┐
│              HOW IS THE FUNCTION CALLED?                     │
├─────────────────────┬───────────────────────────────────────┤
│ Calling Pattern      │ What `this` refers to                │
├─────────────────────┼───────────────────────────────────────┤
│ obj.method()         │ obj (the object before the dot)      │
│ function()           │ global object (or undefined strict)  │
│ arrow function       │ inherited from surrounding scope     │
│ new Constructor()    │ the new object being created         │
│ .call(obj) / .apply(obj) │ explicitly set to obj           │
│ .bind(obj)           │ permanently set to obj               │
├─────────────────────┴───────────────────────────────────────┤
│                                                             │
│  The SIMPLE RULE: Look at what's LEFT of the dot.           │
│  person.greet() → this = person                             │
│  car.start()    → this = car                                │
│  greet()        → this = ??? (no dot = global/undefined)    │
│                                                             │
└─────────────────────────────────────────────────────────────┘

Enter fullscreen mode Exit fullscreen mode


Arrow Functions and this — The Exception

Arrow functions are the one case where the "who's calling" rule doesn't apply. Arrow functions don't have their own this. They permanently inherit this from whatever scope they were defined in.

const team = {
  name: "ChaiCode",
  members: ["Pratham", "Arjun", "Priya"],
  listMembers() {
    // Arrow function inherits `this` from listMembers()
    this.members.forEach((member) => {
      console.log(`${member} is on team ${this.name}`);
    });
  },
};

team.listMembers();
// "Pratham is on team ChaiCode"
// "Arjun is on team ChaiCode"
// "Priya is on team ChaiCode"

Enter fullscreen mode Exit fullscreen mode

If we used a regular function inside forEach, this.name would be undefined because the callback wouldn't have team as its caller. Arrow functions bypass this problem entirely.

When NOT to Use Arrow Functions

Don't use arrow functions as object methods:

// ❌ Bad — arrow function as method
const user = {
  name: "Pratham",
  greet: () => {
    console.log(`Hi, ${this.name}`); // undefined!
  },
};

user.greet(); // "Hi, undefined"

Enter fullscreen mode Exit fullscreen mode

Why? Because the arrow function doesn't get this from user. It inherits this from the surrounding scope, which is the global scope. And this.name in the global scope is undefined.

// ✅ Good — regular function as method
const user = {
  name: "Pratham",
  greet() {
    console.log(`Hi, ${this.name}`); // "Pratham"
  },
};

Enter fullscreen mode Exit fullscreen mode

Rule of thumb: Use regular functions for object methods. Use arrow functions for callbacks inside those methods.


Let's Practice: Hands-On Assignment

Part 1: this in Object Methods

const student = {
  name: "Pratham",
  course: "Web Dev Cohort 2026",
  introduce() {
    console.log(`I'm ${this.name}, enrolled in ${this.course}`);
  },
};

student.introduce(); // "I'm Pratham, enrolled in Web Dev Cohort 2026"

Enter fullscreen mode Exit fullscreen mode

Part 2: Same Function, Different Callers

function displayInfo() {
  console.log(`${this.title} by ${this.author}`);
}

const book1 = { title: "Clean Code", author: "Robert Martin", displayInfo };
const book2 = { title: "Eloquent JS", author: "Marijn Haverbeke", displayInfo };

book1.displayInfo(); // "Clean Code by Robert Martin"
book2.displayInfo(); // "Eloquent JS by Marijn Haverbeke"

Enter fullscreen mode Exit fullscreen mode

Part 3: The Lost Context Problem

const app = {
  name: "FeedPulse",
  start() {
    console.log(`${this.name} is starting...`);
  },
};

app.start(); // "FeedPulse is starting..." ✅

const startFn = app.start;
startFn(); // "undefined is starting..." ❌ — context lost!

Enter fullscreen mode Exit fullscreen mode

Part 4: Arrow Function Fix

const playlist = {
  name: "Chill Vibes",
  songs: ["Lo-fi Beat", "Ocean Waves", "Night Drive"],
  display() {
    this.songs.forEach((song) => {
      console.log(`${song} — from "${this.name}"`);
    });
  },
};

playlist.display();
// "Lo-fi Beat — from "Chill Vibes""
// "Ocean Waves — from "Chill Vibes""
// "Night Drive — from "Chill Vibes""

Enter fullscreen mode Exit fullscreen mode


Key Takeaways

  1. this refers to the object that is calling the function. Ask: "What's to the left of the dot?"
  2. In the global context, this is the global object (window in browsers). In strict mode standalone functions, this is undefined.
  3. Inside object methods, this is the object that owns the method. user.greet()this = user.
  4. In regular standalone functions, this loses its context and falls back to global. Extracting a method from an object also loses context.
  5. Arrow functions don't have their own this — they inherit it from the surrounding scope. Use them for callbacks, not for object methods.

Wrapping Up

this is one of those concepts that seems unnecessarily complicated until you learn the one rule that governs it: this is determined by the caller, not the author. Once that clicks, you stop guessing and start knowing what this will be in any situation.

I'm working through these concepts in the ChaiCode Web Dev Cohort 2026 under Hitesh Chaudhary and Piyush Garg, and understanding this became critical the moment we started working with object methods, event handlers, and class-based patterns. It's a fundamental piece of JavaScript that touches everything.

Connect with me on LinkedIn or visit PrathamDEV.in. More articles on the way as I keep building and learning.

Happy coding! 🚀


Written by Pratham Bhardwaj | Web Dev Cohort 2026, ChaiCode