← Back to JavaScript Course | Chapter 6: Functions Advanced | Lesson 3 of 8

JS this Keyword

this in an Object

Inside an object method, this usually refers to the object that called the method. If the same method is later assigned to a different object or called standalone, this changes accordingly since it's determined by the call, not by where the function was defined.

Example: this in an Object

javascript
const user = {
  name: "Sam",
  greet() {
    console.log(this.name);
  },
};
user.greet(); // this === user

this in a Regular Function

The value of this in a regular function depends on how the function is called. In strict mode, a plain function call has this as undefined. In non-strict mode, that same plain call instead defaults this to the global object, which is one reason strict mode's stricter behavior is generally preferred.

Example: this in a Regular Function

javascript
function show() {
  "use strict";
  console.log(this); // undefined in strict mode
}
show();

this in Arrow Functions

Arrow functions do not create their own this. They use this from the surrounding scope. This is exactly why arrow functions are often used for callbacks inside methods — they inherit the outer this instead of losing it when the callback is invoked elsewhere.

Example: this in Arrow Functions

javascript
const user = {
  name: "Sam",
  greet() {
    setTimeout(() => console.log(this.name), 0); // arrow inherits this
  },
};
user.greet();

this With Classes

In a class method, this normally refers to the current object instance. This is why arrow functions make poor choices for object methods themselves: since they don't bind their own this, they'd inherit this from the class body's surrounding scope instead of the instance.

Example: this With Classes

javascript
class User {
  constructor(name) { this.name = name; }
  greet() { console.log(this.name); } // this === instance
}
new User("Amit").greet();

Practice

When using this, first check how the function is called. That usually tells you what this refers to. If a function's this value seems wrong, call/apply/bind can explicitly override it, which is often the fastest way to confirm what's actually happening.

Example: Practice

javascript
const user = { name: "Sam" };
function show() { console.log(this.name); }
show.call(user); // confirms this === user
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.