Mastering 'this' in JavaScript: Understand Context, Call, Apply, and Bind with Real Examples

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.

function show() {
console.log(this); } show(); // In browser: window (global object)

In strict mode ('use strict'), this becomes undefined in regular functions when not called on an object.

2️⃣ this in Different Contexts

🔸 Global Context


console.log(this); // window (in browser)

🔸 Inside a Method

const person = { name: "Techie-tides", greet() { console.log(`Hi, This is ${this.name}`); } }; person.greet(); // Hi, This is Techie-tides

🔸 Inside a Regular Function


function test() { console.log(this); } test(); // window (in browser), undefined in strict mode

🔸 Arrow Functions (No this binding)

Arrow functions capture this from the surrounding lexical scope.


const obj = { name: "Techie-tides", greet: () => { console.log(this.name); } }; obj.greet(); // undefined

🧠 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

function greet(lang) { console.log(`${lang}: Hello, ${this.name}`); } const user = { name: "Ram" }; greet.call(user, "EN"); // EN: Hello, Ram

🔹 apply(): Similar to call(), but arguments are passed as an array

greet.apply(user, ["FR"]); // FR: Hello, Sriram

🔹 bind(): Returns a new function with this bound

const greetUser = greet.bind(user, "HI"); greetUser(); // HI: Hello, Ram

4️⃣ Common Pitfalls with this

  • Losing context when passing methods as callbacks


const person = { name: "Ram", speak() { console.log(this.name); } }; setTimeout(person.speak, 1000); // undefined (lost `this`)

Fix with arrow or bind:

setTimeout(() => person.speak(), 1000);

Or bind manually:

setTimeout(person.speak.bind(person), 1000);


5️⃣ Real-Life Use Cases and Best Practices

✅ Use bind() in event handlers
✅ Use arrow functions in React components or nested functions to retain this
✅ Use call() and apply() for method borrowing or invoking functions on different objects

Example – Method Borrowing:

const car = { brand: "Tesla" };
function display() { console.log(`Brand is ${this.brand}`); } display.call(car); // Brand is Tesla




This Content Sponsored by Buymote Shopping app

BuyMote E-Shopping Application is One of the Online Shopping App

Now Available on Play Store & App Store (Buymote E-Shopping)

Click Below Link and Install Application: https://buymote.shop/links/0f5993744a9213079a6b53e8

Sponsor Content: #buymote #buymoteeshopping #buymoteonline #buymoteshopping #buymoteapplication



Previous Post Next Post