How does the `this` keyword work in JavaScript and when should it be used?
Hello everyone! I'm a beginner in JavaScript and I'm constantly confused with the `this` keyword. I've read the documentation, but it seems too complicated. I have this code:\n\n```javascript\nconst user = {\n name: 'Anna',\n greet: function() {\n console.log('Hello, ' + this.name);\n }\n};\n\nconst greetFunc = user.greet;\nuser.greet(); // Outputs "Hello, Anna" — works!\ngreetFunc(); // Outputs "Hello, undefined" — why?\n```\n\nWhen I call `user.greet()`, everything works. But if I save the method to a variable and call it, `this.name` becomes `undefined`. Why does this happen? Also: I've heard that `this` behaves differently in arrow functions and regular functions. How can I understand what `this` will refer to in my code? When should I use `this`, and when is it better to pass an obje
No answers yet.
Log in to leave an answer
Blogs