Day 1: Everything You Need to Know About this in JavaScript
Overview of this
1. this in Global Scope
Example (featuring Deepak): Deepak writes a function but forgets its context.
function showThis() {
console.log(this);
}
showThis(); // Non-strict: Window | Strict: undefined
2. this in Object Methods
Example (Deepak and his recipe): Deepak, the chef, refers to his own secret sauce.
const chef = {
name: 'Deepak Sharma',
cook() {
console.log(this.name + ' is cooking!');
},
};
chef.cook(); // Output: Deepak Sharma is cooking!
const cookFunc = chef.cook;
cookFunc(); // Output: undefined
const boundCook = chef.cook.bind(chef);
boundCook(); // Output: Deepak Sharma is cooking!
3. this in Arrow Functions
Example (Deepak's parrot): Deepak’s parrot repeats everything Deepak says.
const parrotOwner = {
name: 'Deepak Sharma',
talk() {
const parrot = () => console.log(this.name + "'s parrot is talking!");
parrot();
},
};
parrotOwner.talk(); // Output: Deepak Sharma's parrot is talking!
4. this in Constructors and Classes
Example (Deepak builds robots):
function Robot(name) {
this.name = name;
}
const wallE = new Robot(Iron-man');
console.log(wallE.name); // Output: Iron man
class Spaceship {
constructor(name) {
this.name = name;
}
launch() {
console.log(this.name + ' is launching!');
}
}
const falcon = new Spaceship('Falcon 9');
falcon.launch(); // Output: Falcon 9 is launching!
5. this in Event Handlers
Example (Deepak presses a button):
document.querySelector('button').addEventListener('click', function () {
console.log(this); // Refers to the button element
});
document.querySelector('button').addEventListener('click', () => {
console.log(this); // Refers to the global object (Window)
});
6. Common Pitfalls and Fixes
6.1. Losing Context in Callbacks
Recommended by LinkedIn
Example (Deepak’s cat Lilly):
const cat = {
name: 'Lilly',
meow() {
console.log(this.name + ' says Meow!');
},
};
setTimeout(cat.meow, 1000); // Output: undefined
setTimeout(cat.meow.bind(cat), 1000); // Output: Lilly says Meow!
6.2. this in Closures
Example (Deepak gets lost in a cave):
const adventurer = {
name: 'Deepak Sharma',
explore() {
function innerEcho() {
console.log(this.name + ' is lost!');
}
innerEcho(); // Output: undefined
},
};
adventurer.explore();
const adventurer = {
name: 'Deepak Sharma',
explore() {
const self = this;
function innerEcho() {
console.log(self.name + ' found the treasure!');
}
innerEcho(); // Output: Deepak Sharma found the treasure!
},
};
adventurer.explore();
const adventurer = {
name: 'Deepak Sharma',
explore() {
const innerEcho = () => console.log(this.name + ' found the treasure!');
innerEcho(); // Output: Deepak Sharma found the treasure!
},
};
adventurer.explore();
7. Explicitly Setting this: call, apply, and bind
7.1. call
function greet(greeting) {
console.log(`${greeting}, ${this.name}`);
}
const wizard = { name: 'Deepak the Wise' };
greet.call(wizard, 'Hello'); // Output: Hello, Deepak the Wise
7.2. apply
greet.apply(wizard, ['Hi']); // Output: Hi, Deepak the Wise
7.3. bind
const boundGreet = greet.bind(wizard, 'Hey');
boundGreet(); // Output: Hey, Deepak the Wise
8. Borrowing Methods
Example (Deepak and superhero calculations):
const hero1 = { powers: [100, 200, 300], avgPower: null };
const hero2 = { powers: [50, 75, 125], avgPower: null };
function calculateAvgPower() {
const sum = this.powers.reduce((a, b) => a + b, 0);
this.avgPower = sum / this.powers.length;
}
calculateAvgPower.call(hero1);
console.log(hero1.avgPower); // Output: 200
calculateAvgPower.apply(hero2);
console.log(hero2.avgPower); // Output: 83.33
9. Summary Table
The value of this is defined at run-time.
Please note that arrow functions are special: they have no this. When this is accessed inside an arrow function, it is taken from outside.
10. Key Takeaways
References
Very helpful
Very Important from Interview Prep. Thanks
Love this
Very informative
Good 💯