The this keyword is a reference to the object that called the current function. Simply put, it’s a way for a function to know “who owns it” or “on whose behalf” it works. 🎯
[this] is one of the most important concepts in JavaScript that often causes confusion. Let’s break it down very simply! 😊
[this] is like a function’s passport. It shows which object the function is bound to:
const user = {
name: 'John',
greet() {
console.log('Hello, ' + this.name); // this → user
}
};const cat = {
name: 'Murka',
meow() {
console.log(this.name + ' meows'); // 'Murka meows'
}
};
cat.meow(); // this → catfunction showThis() {
console.log(this); // depends on execution mode
}
showThis(); // undefined (in strict mode)const person = {
name: 'Peter',
sayName() {
return this.name; // 'Peter'
}
};
person.sayName(); // this → personconst person = {
name: 'Peter',
sayName() {
return this.name;
}
};
const func = person.sayName;
func(); // this → undefined (in strict mode) ❌const counter = {
value: 0,
increment() {
this.value++; // changing object property
}
};const dog = {
name: 'Sharik',
sound: 'woof'
};
const bird = {
name: 'Chizhik',
sound: 'chirp'
};
function makeSound() {
console.log(this.name + ' says ' + this.sound);
}
// One function works for different objects!
makeSound.call(dog); // 'Sharik says woof'
makeSound.call(bird); // 'Chizhik says chirp'const obj = {
name: 'John',
greet() {
console.log('Hello, ' + this.name);
}
};
const greetFunc = obj.greet;
greetFunc(); // 'Hello, undefined' ❌const obj = {
name: 'John',
// Arrow function doesn't have its own this
arrowFunc: () => {
console.log(this.name); // undefined
}
};Understanding [this] helps write more predictable code and avoid errors. This is a very important topic for any JavaScript developer! 💪
Want more articles to prepare for interviews? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪