JavaScript Tutorial in Hindi #24 | What is 'this' in JavaScript? (2025)
✅ 1. What is this
in JavaScript?
The this
keyword refers to the object that is executing the current function.
But the value of this
depends on how the function is called, not where it's defined.
✅ 2. How this
Behaves in Different Contexts
Let’s explore it step by step:
✅ 3. this
in the Global Scope
In browsers, this
refers to the global object, which is window
.
js
CopyEdit
console.log(this); // window (in browser)
✅ 4. this
Inside a Regular Function
js
CopyEdit
function show() {
console.log(this);
}
show(); // In non-strict mode: window; In strict mode: undefined
- In non-strict mode,
this
refers to the global object. - In strict mode, it’s
undefined
.
✅ 5. this
Inside an Object Method
js
CopyEdit
let user = {
name: "Mohit",
greet() {
console.log("Hello, " + this.name);
}
};
user.greet(); // "Hello, Mohit"
✅ Inside methods, this
refers to the object calling the method.
✅ 6. this
with Arrow Functions
Arrow functions do not have their own this
. They inherit this
from the parent scope (lexical scope).
js
CopyEdit
let user = {
name: "Mohit",
greet: () => {
console.log("Hello, " + this.name);
}
};
user.greet(); // "Hello, undefined" (because arrow functions use outer `this`)
✅ Use regular functions for methods if you need access to the object’s this
.
✅ Example to Compare:
js
CopyEdit
let user = {
name: "Mohit",
regularFunc: function () {
console.log("Regular:", this.name);
},
arrowFunc: () => {
console.log("Arrow:", this.name);
}
};
user.regularFunc(); // "Regular: Mohit"
user.arrowFunc(); // "Arrow: undefined"
✅ BONUS: Controlling this
with call()
, apply()
, and bind()
js
CopyEdit
function greet() {
console.log("Hello, " + this.name);
}
let user = { name: "Alice" };
greet.call(user); // "Hello, Alice"
greet.apply(user); // "Hello, Alice"
let greetUser = greet.bind(user);
greetUser(); // "Hello, Alice"