Mastering 'this' in JavaScript: Understand Context, Call, Apply, and Bind with Real Examples
1️⃣ What is this
in JavaScript?
The value of this
depends on how a function is called, not where it is defined. It's a dynamic reference to the object that is executing the function.
In strict mode (
'use strict'
),this
becomesundefined
in regular functions when not called on an object.
2️⃣ this
in Different Contexts
🔸 Global Context
🔸 Inside a Method
🔸 Inside a Regular Function
🔸 Arrow Functions (No this
binding)
Arrow functions capture this
from the surrounding lexical scope.
🧠 Arrow functions do not have their own
this
– they inherit from the parent scope.
3️⃣ Controlling this
with call
, apply
, and bind
🔹 call()
: Invokes a function, setting this
and passing arguments one by one
🔹 apply()
: Similar to call()
, but arguments are passed as an array
🔹 bind()
: Returns a new function with this
bound