How to properly access `this` inside a callback function in JavaScript?
Hello everyone! I just started learning JavaScript and encountered a problem that I can't solve. I have an object `user` with a property `name` and a method `greet`. I want the `greet` method to output a greeting with the user's name after 2 seconds. For this I use `setTimeout`. But when I run the code, it outputs `undefined` instead of the name. Here's my code:
```javascript
const user = {
name: 'Anna',
greet: function() {
setTimeout(function() {
console.log(`Hello, ${this.name}!`);
}, 2000);
}
};
user.greet(); // Outputs "Hello, undefined!"
```
I understand that the problem is that inside the callback function in `setTimeout` the context `this` is lost. But I don't understand why this happens and how to fix it. I tried reading the documentation, but there
No answers yet.
Log in to leave an answer