Explain ‘this’ keyword in JavaScript
Explain 'this' keyword in JavaScript
In JavaScript, the this keyword is one of the most confusing topics for beginners because it behaves differently from how people expect in other languages. But once you understand what decides the value of this (the call site, not the definition site), it becomes consistent and logical.
Think of this as a reference to the current "owner" of the function call - the object that the function is being executed "on."
But JavaScript does not decide this when you write the function - it decides it each time the function is called, depending on how the function is called.
1. Global context
When you use this in the global scope (outside of any function), the value depends on the environment and mode.
In a browser, outside of strict mode, this refers to the global object - that's window.
In Node.js, it refers to an empty object in modules, not the global object.
In strict mode, this is undefined in global functions.
console.log(this === window); // true (in browsers, non-strict mode)
If you add "use strict"; at the top, then inside a normal function that isn't attached to an object:
"use strict";
function show() {
console.log(this);
}
show(); // undefined
So the first rule is:
- In normal (non-strict) mode, this defaults to the global object.
- In strict mode, it becomes undefined.
2. Inside methods (object functions)
If a function is called as a property of an object, this points to that object.
const user = {
name: "Alice",
greet() {
console.log("Hi, I'm " + this.name);
},
};
user.greet(); // "Hi, I'm Alice"