JS this Keyword
In this page:
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
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
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
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
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
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: